【问题标题】:Python 3.2: How to pass a dictionary into str.format()Python 3.2:如何将字典传递给 str.format()
【发布时间】:2011-09-23 04:04:23
【问题描述】:

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

这是我想要做的:

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

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

【问题讨论】:

标签: python-3.x dictionary string-formatting keyword-argument


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    这样就可以了:

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

    更多信息请参考:

    【讨论】:

    • 为什么这个获得的票数较少?它有更多信息(文档链接)和更好的示例。
    猜你喜欢
    • 1970-01-01
    • 2019-02-11
    • 2016-12-22
    • 1970-01-01
    • 2022-08-09
    • 1970-01-01
    • 1970-01-01
    • 2014-01-21
    相关资源
    最近更新 更多