Python 3.2:如何将字典传递给str.format()

问题描述 投票:23回答:2

我一直在阅读有关字符串格式的Python 3.2文档,但它并没有真正帮助我解决这个特殊问题。

这是我正在尝试做的事情:

stats = { 'copied': 5, 'skipped': 14 }
print( 'Copied: {copied}, Skipped: {skipped}'.format( stats ) )

上面的代码不起作用,因为format()调用不是读取字典值并使用它们代替我的格式占位符。如何修改我的代码以使用我的字典?

python-3.x dictionary string-formatting kwargs
2个回答
46
投票

这样做的工作:

stats = { 'copied': 5, 'skipped': 14 }
print( 'Copied: {copied}, Skipped: {skipped}'.format( **stats ) )  #use ** to "unpack" a dictionary

欲了解更多信息,请参阅:


15
投票

你想要.format(**stats),因为这会使统计数据成为格式化的一部分。

© www.soinside.com 2019 - 2024. All rights reserved.