python format函数冒号_Python: 字符串格式化format()函数的使用

举例说明:

①复杂数据格式化

>>> data=[4,8,15,16,23,42]

>>> '{d[4]}{d[5]}'.format(d=data)

'2342'

>>>

②复杂数据格式化:

>>> class Plant(object):

... type='tree'

... kinds=[{'name':'oak'},{'name':'maple'}]

...

>>> '{p.type}:{p.kinds[0][name]}'.format(p=Plant())

'tree:oak'

>>>

③分类举例说明,

花括号声明{}、用于渲染前的参数引用声明, 花括号里可以用数字代表引用参数的序号, 或者 变量名直接引用。

>>> '{}{}'.format('one','two')

'onetwo'

>>> '{1}{0}'.format('one','two')

'twoone'

>>>

④通过字典的key取value

>>> '{first}{last}'.format(**data)

'Hodorhordor!'

>>>

⑤从format参数引入的变量名 、冒号:、字符位数声明、空白自动填补符 的声明、千分位的声明、变量类型的声明: 字符串s、数字d、浮点数f 、对齐方向符号 < ^ >

>>> '{first}{last}'.format(**data)

'Hodorhordor!'

>>> '{:.5}'.format('xylophone')

'xylop'

>>> '{:^10}'.format('test')

' test '

>>> '{:.{}}'.format('xylophone',7)

'xylopho'

>>> '{:4d}'.format(42)

' 42'

>>> '{:6.2f}'.format(3.1415926)

' 3.14'

>>> '{:06.2f}'.format(3.1415926)

'003.14'

>>>

⑥千分位、浮点数、填充字符、对齐的组合使用:

>>> '{:>18,.2f}'.format(70305084.0)

' 70,305,084.00'

>>> '{:>18.2f}'.format(70305084.0)

' 70305084.00'

>>>

⑦属性访问符中括号 ☐

>>> '{p[first]} {p[last]}'.format(p=person)

'Jean-Luc Picard'

>>>

⑧惊叹号!限定访问__repr__等魔法函数:

>>> class Data(object):

... def __str__(self):

... return 'str'

... def __repr__(self):

... return 'repr'

...

>>> '{0!s}{0!r}'.format(Data())

'strrepr'

>>>

⑨增加类魔法函数__format__(self, format) , 可以根据format前的字符串格式来定制不同的显示, 如: ’{:xxxx}’ 此时xxxx会作为参数传入__format__函数中。

>>> class HAL9000(object):

... def __format__(self,format):

... if(format == 'open-the-pod-bay-doors'):

... return "I'm afraid I can't do that"

... return 'HAL 9000'

...

>>> '{:open-the-pod-bay-doors}'.format(HAL9000())

"I'm afraid I can't do that"

>>>

⑩时间日期的特例:

>>> from datetime import datetime

>>> '{:%Y-%m-%d %H:%M}'.format(datetime(2001,2,3,4,5))

'2001-02-03 04:05'

>>>

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值