预约成功
如果在 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.
如果你有一个非常长的格式字符串,你不想把它拆开,那么你最好按名称而不是位置引用变量来进行格式化。这可以通过简单地传递字典和使用方括号 '[]' 访问键来完成:
>>>>>> 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}
>>> print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678
这在与内置函数 vars() 结合使用时非常有用,它会返回包含所有局部变量的字典。
以上就是本章内容,希望对您的python学习之路有所帮助。