[英]String interpolation working with python
我剛開始學習如何在字符串中使用字符串插值,並且在獲取要實際打印正確結果的示例時遇到了麻煩。
我試着做:
print "My name is {name} and my email is {email}".format(dict(name="Jeff", email="me@mail.com"))
它說KeyError: 'name'
時出錯
然后我嘗試使用:
print "My name is {0} and my email is {0}".format(dict(name="Jeff", email="me@mail.com"))
它打印
My name is {'email': 'me@mail.com', 'name': 'Jeff'} and my email is {'email': 'me@mail.com', 'name': 'Jeff'}
因此,我嘗試這樣做:
print "My name is {0} and my email is {1}".format(dict(name="Jeff", email="me@mail.com"))
它錯誤地說IndexError: tuple index out of range
它應該給我以下輸出結果:
My name is Jeff and my email is me@mail.com
謝謝。
只需刪除對dict
的調用即可:
>>> print "My name is {name} and my email is {email}".format(name="Jeff", email="me@mail.com")
My name is Jeff and my email is me@mail.com
>>>
這是有關字符串格式化的語法的參考。
您缺少[]
( getitem
)運算符。
>>> print "My name is {0[name]} and my email is {0[email]}".format(dict(name="Jeff", email="me@mail.com"))
My name is Jeff and my email is me@mail.com
或者不調用dict
使用它
>>> print "My name is {name} and my email is {email}".format(name='Jeff', email='me@mail.com')
My name is Jeff and my email is me@mail.com
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.