我刚开始学习如何在字符串中使用字符串插值,但在获取我正在使用的示例以实际打印正确结果时遇到了问题。
我试过:
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
>>>
这是关于 string formatting 语法的引用.
