Skip to main content
 首页 » 编程设计

python-3.x之Python 3.2 : How to pass a dictionary into str. 格式()

2024年11月24日19unruledboy

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

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

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

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

请您参考如下方法:

这可以完成工作:

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

更多信息请引用:
  • http://docs.python.org/py3k/library/string.html#format-examples
  • http://docs.python.org/py3k/tutorial/controlflow.html#keyword-arguments