python format函数冒号

编程入门 行业动态 更新时间:2024-10-10 10:25:24

python format函数<a href=https://www.elefans.com/category/jswz/34/1706721.html style=冒号"/>

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'

>>>

更多推荐

python format函数冒号

本文发布于:2024-03-23 21:46:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1743206.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:冒号   函数   python   format

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!