2013-12-17 74 views
1

我是新來學習如何在字符串中使用字符串插值,並且無法獲取此示例,我正在使用它來實際打印正確的結果。使用python進行字符串插值

我試圖做的事:

print "My name is {name} and my email is {email}".format(dict(name="Jeff", email="[email protected]")) 

它錯誤說​​

然後我試着使用:

print "My name is {0} and my email is {0}".format(dict(name="Jeff", email="[email protected]")) 

而且它打印

My name is {'email': '[email protected]', 'name': 'Jeff'} and my email is {'email': '[email protected]', 'name': 'Jeff'} 

小號Ø然後我試圖做的:

print "My name is {0} and my email is {1}".format(dict(name="Jeff", email="[email protected]")) 

它錯誤說IndexError: tuple index out of range

應該給我下面的輸出結果返回:

My name is Jeff and my email is [email protected] 

感謝。

回答

8

只需刪除調用dict

>>> print "My name is {name} and my email is {email}".format(name="Jeff", email="[email protected]") 
My name is Jeff and my email is [email protected] 
>>> 

這裏是關於語法string formatting參考。

+0

感謝。所以你不必使用字典? – user3079411

+0

@ user3079411 - 不,不適用於'str.format'。如果你有一本字典,你可以像@hwnd所示。但在你的情況下,調用'dict'是不必要的。 – iCodez

+0

哦,好吧,我現在明白了。非常感謝。 – user3079411