【发布时间】: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
这段代码有什么问题?
dic = { 'fruit': 'apple', 'place':'table' }
test = "I have one {fruit} on the {place}.".format(dic)
print(test)
>>> KeyError: 'fruit'
【问题讨论】:
标签: python dictionary
从 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)
【讨论】:
【讨论】:
**?
** 表示字典应该扩展为关键字参数列表。 format 方法不接受字典作为参数,但它确实接受关键字参数。
dic = {'a':1,'b':2,'c':3} 并调用f(**dic)。
"I have one {0[fruit]} on the {0[place]}.".format(dic) 也可以工作——dic 是这里的第 0 个位置参数,您可以在模板中访问它的键。
您也可以使用以下代码:
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 3.1 中弃用,但他们从未这样做过。它不会很快消失(或者可能根本不会消失),所以仍然可以使用它。
format,首先是因为它是推荐的,其次是因为它看起来更干净。