【问题标题】:How to use str.format() with a dictionary in python?如何在 python 中将 str.format() 与字典一起使用?
【发布时间】:2011-09-07 22:48:50
【问题描述】:

这段代码有什么问题?

dic = { 'fruit': 'apple', 'place':'table' }
test = "I have one {fruit} on the {place}.".format(dic)
print(test)

>>> KeyError: 'fruit'

【问题讨论】:

标签: python dictionary


【解决方案1】:

从 Python 3.2 开始就有''.format_map() function

test = "I have one {fruit} on the {place}.".format_map(dic)

优点是它接受任何映射,例如,具有动态生成值的__getitem__ 方法的类或允许您使用不存在的键的collections.defaultdict

可以在旧版本上模拟:

from string import Formatter

test = Formatter().vformat("I have one {fruit} on the {place}.", (), dic)

【讨论】:

    【解决方案2】:

    应该是

    test = "I have one {fruit} on the {place}.".format(**dic)
    

    注意**format() 不接受单个字典,而是接受关键字参数。

    【讨论】:

    • 谢谢,它有效。您能否更新答案以解释为什么我必须在字典前添加**
    • @bogdan,** 表示字典应该扩展为关键字参数列表。 format 方法不接受字典作为参数,但它确实接受关键字参数。
    • @bogdan:在我的答案中添加了两个链接。原因基本上是“因为文档是这样说的”。
    • @bogdan 这只是告诉 Python 您正在为函数提供字典,以便它可以提供字典中的值,而不是字典本身。调用任何函数时都可以这样做。如果函数“f”采用参数“a”、“b”和“c”,则可以使用dic = {'a':1,'b':2,'c':3} 并调用f(**dic)
    • 原因是"I have one {0[fruit]} on the {0[place]}.".format(dic) 也可以工作——dic 是这里的第 0 个位置参数,您可以在模板中访问它的键。
    【解决方案3】:

    您也可以使用以下代码:

    dic = { 'fruit': 'apple', 'place':'table' }
    print "I have one %(fruit)s on the %(place)s." % dic
    

    如果您想了解更多关于格式方法的使用:http://docs.python.org/library/string.html#formatspec

    【讨论】:

    • 根据 Python 文档,% 运算符不应在新代码中使用。
    • 能否请您给我一个参考,以便我能够阅读更多关于此的内容?
    • 非常感谢),以后尽量避免使用
    • @Mark: % 本来打算在 Python 3.1 中弃用,但他们从未这样做过。它不会很快消失(或者可能根本不会消失),所以仍然可以使用它。
    • @Sven,很高兴知道,谢谢。我还是会选择format,首先是因为它是推荐的,其次是因为它看起来更干净。
    猜你喜欢
    • 2011-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-20
    • 1970-01-01
    • 2015-12-05
    • 1970-01-01
    相关资源
    最近更新 更多