這段代碼有什麼問題?如何使用str.format()與Python中的字典?
dic = { 'fruit': 'apple', 'place':'table' }
test = "I have one {fruit} on the {place}.".format(dic)
print(test)
>>> KeyError: 'fruit'
這段代碼有什麼問題?如何使用str.format()與Python中的字典?
dic = { 'fruit': 'apple', 'place':'table' }
test = "I have one {fruit} on the {place}.".format(dic)
print(test)
>>> KeyError: 'fruit'
您可以使用下面的代碼太好處是它可以接受任何映射,例如,一個具有動態生成值的__getitem__
方法的類或collections.defaultdict
讓你使用不存在的鍵。
它可以在舊版本進行仿真:
from string import Formatter
test = Formatter().vformat("I have one {fruit} on the {place}.",(), dic)
根據Python文檔,不應該在新代碼中使用'%'運算符。 – 2011-06-03 16:13:11
您能否給我一個參考,以便我能夠閱讀更多關於這方面的內容? – 2011-06-03 16:14:10
很高興:http://docs.python.org/release/2.6.6/library/stdtypes.html#str.format – 2011-06-03 16:17:07
有''.format_map()
function因爲Python 3.2:
test = "I have one {fruit} on the {place}.".format_map(dic)
的
謝謝,它的工作原理。你能否更新答案來解釋爲什麼我必須在字典前添加'**'? – bogdan 2011-06-03 16:08:35
@bogdan,'**'表示字典應該擴展爲關鍵字參數列表。 'format'方法不會將字典作爲參數,但它確實需要關鍵字參數。 – 2011-06-03 16:14:48
@bogdan:添加了兩個鏈接到我的答案。原因基本上是「因爲文檔如此說」。 – 2011-06-03 16:14:59