python菜鸟教程format_Pythonformat格式化函数
如果在 str.format() 调⽤时使⽤关键字参数,可以通过参数名来引⽤值:
>>> print('This {food} is {adjective}.'.format(
... food='spam', adjective='absolutely horrible'))
This spam is absolutely horrible.
位置参数和关键字参数可以随意组合:
>>> print('The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred', other='Georg'))
The story of Bill, Manfred, and Georg.
!a (应⽤ ascii()), !s (应⽤str() )和 !r (应⽤ repr() )可以在格式化之前转换值:
>>> import math
>>> print('The value of PI is approximately {}.'.format(math.pi))
The value of PI is approximately 3.14159265359.
>>> print('The value of PI is approximately {!r}.'.format(math.pi))
The value of PI is approximately 3.141592653589793.
字段名后允许可选的 : 和格式指令。这允许对值的格式化加以更深⼊的控制。下例将 Pi 转为三位精度。
>>> import math
>>> print('The value of PI is approximately {0:.3f}.'.format(math.pi))
The value of PI is approximately 3.142.
在字段后的 : 后⾯加⼀个整数会限定该字段的最⼩宽度,这在美化表格时很有⽤:
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
>>> for name, phone in table.items():
... print('{0:10} ==> {1:10d}'.format(name, phone))
...
Jack ==> 4098
Dcab ==> 7678
Sjoerd ==> 4127
如果你有个实在是很长的格式化字符串,不想分割它。如果你可以⽤命名来引⽤被格式化的变量⽽不是位置就好了。有个简单的⽅法,可以传⼊⼀个字典,⽤中括号( [] )访问它的键:
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; '
'Dcab: {0[Dcab]:d}'.format(table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678
也可以⽤ ** 标志将这个字典以关键字参数的⽅式传⼊:
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
python菜鸟教程文档>>> print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table)) Jack: 4098; Sjoerd: 4127; Dcab: 8637678
嘟⼩三
嘟⼩三
Xx1***516009@1632年前 (2018-10-18)

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。