这段代码有什么问题?
dic = { 'fruit': 'apple', 'place':'table' }
test = "I have one {fruit} on the {place}.".format(dic)
print(test)
>>> KeyError: 'fruit'
这段代码有什么问题?
dic = { 'fruit': 'apple', 'place':'table' }
test = "I have one {fruit} on the {place}.".format(dic)
print(test)
>>> KeyError: 'fruit'
**
吗? - bogdanformat
方法不接受字典作为参数,但它可以接受关键字参数。 - Mark Ransomdic = {'a':1,'b':2,'c':3}
并调用f(**dic)
。 - Michael Smith"我在{0[place]}上有一个{0[fruit]}。".format(dic)
也可以运行 - 这里的 dic
是第0个位置参数,你可以在模板中访问它的键。 - Jochen Ritzel自Python 3.2开始,就有了 ''.format_map()
函数:
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)
dic = { 'fruit': 'apple', 'place':'table' }
print "I have one %(fruit)s on the %(place)s." % dic
如果您想了解更多关于格式化方法的信息,请参考:http://docs.python.org/library/string.html#formatspec
%
运算符。 - Mark Ransom%
在 Python 3.1 中应该被弃用,但他们从未这样做。它不会很快消失(或者可能根本不会消失),所以仍然可以使用它。 - Sven Marnachformat
,因为它被推荐使用,其次因为它看起来更简洁。 - Mark Ransomlogging.debug("Message with %(expensive_out)s" % expensive_out=expensive_func())
如果使用f-string格式,则只会调用expensive_func()
以将构造的字符串丢弃(假设已禁用调试日志记录)。 - Ajay M