2011-06-03 37 views

回答

25

應該

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

注意**format()不接受單個字典,而是接受關鍵字參數。如果您想了解更多關於格式的方法使用

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

http://docs.python.org/library/string.html#formatspec

+0

謝謝,它的工作原理。你能否更新答案來解釋爲什麼我必須在字典前添加'**'? – bogdan 2011-06-03 16:08:35

+2

@bogdan,'**'表示字典應該擴展爲關鍵字參數列表。 'format'方法不會將字典作爲參數,但它確實需要關鍵字參數。 – 2011-06-03 16:14:48

+0

@bogdan:添加了兩個鏈接到我的答案。原因基本上是「因爲文檔如此說」。 – 2011-06-03 16:14:59

0

您可以使用下面的代碼太好處是它可以接受任何映射,例如,一個具有動態生成值的__getitem__方法的類或collections.defaultdict讓你使用不存在的鍵。

它可以在舊版本進行仿真:

from string import Formatter 

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

根據Python文檔,不應該在新代碼中使用'%'運算符。 – 2011-06-03 16:13:11

+0

您能否給我一個參考,以便我能夠閱讀更多關於這方面的內容? – 2011-06-03 16:14:10

+0

很高興:http://docs.python.org/release/2.6.6/library/stdtypes.html#str.format – 2011-06-03 16:17:07