2016-11-26 95 views
0

我試圖在Python 2.7版和:Python:如何讓字符串格式使用字典查找?

b={'name':'abc',address:'xyz'} 
print 'hello %(name)' % b 
--------------------------------------------------------------------------- 
TypeError         Traceback (most recent call last) 
<ipython-input-92-bc9585e20f74> in <module>() 
----> 1 'hello %(name)' % b 

我希望這個聲明將顯示hello abc,如何糾正呢?

回答

1

你應該嘗試這樣

b={'name':'abc','address':'xyz'} 
print 'hello %s' % b['name'] 
+0

沒有必要變量'address'轉換爲字符串,完全改變了代碼。很顯然,OP使用「地址」,否則他會得到不同的錯誤。 – Anthon

+0

哦..好吧..明白了。感謝您的評論 – Prabhakar

4

你缺少一個「s」閉幕)後:

print 'hello %(name)s' % b 

,因爲它似乎你是新的蟒蛇,你應該爲未來做準備並開始使用from __future__ import print_function以及使用@Lolgast已經指出的.format()

from __future__ import print_function 

b = {'name':'abc', address:'xyz'} 
print('hello {name}'.format(**b)) 
+0

爲什麼'''from __future__ import print_function'''?雖然我已經將它用於某些特定目的,但正常的2.7行爲通常很好。我會說,準備未來(如果有必要)將通過切換到python 3一起完成。 – Lolgast

+0

@Lolgast就像我指出的那樣,您應該爲未來的海事組織做好準備。 Python 2.7是支持'print'作爲語句的最後一個版本。在某些時候,你需要兼容/使用/切換到3.x,然後'print()'是強制性的,並且你習慣於忽略'()'。 – Anthon

2

可以使用string.format功能:

b={'name':'abc',address:'xyz'} 
print 'hello {name}'.format(**b)  #Note that you need to explode the dict