Python: 字符串格式化format()函数的使用

 python从2.6开始支持format,新的更加容易读懂的字符串格式化方法,从原来的% 模式变成新的可读性更强的

    花括号声明{}、用于渲染前的参数引用声明, 花括号里可以用数字代表引用参数的序号, 或者 变量名直接引用。
    从format参数引入的变量名 、
    冒号:、
    字符位数声明、
    空白自动填补符 的声明
    千分位的声明
    变量类型的声明: 字符串s、数字d、浮点数f
    对齐方向符号 < ^ >
    属性访问符中括号 ☐
    使用惊叹号!后接a 、r、 s,声明 是使用何种模式, acsii模式、引用__repr__ 或 __str__
    增加类魔法函数__format__(self, format) , 可以根据format前的字符串格式来定制不同的显示, 如: ’{:xxxx}’  此时xxxx会作为参数传入__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'
>>> 
原文地址:https://www.cnblogs.com/baxianhua/p/9131556.html