使用python进行字符串插值
我刚开始学习如何在字符串中使用字符串插值,我很难得到我正在使用的这个示例来实际打印正确的结果 我试着做:使用python进行字符串插值,python,Python,我刚开始学习如何在字符串中使用字符串插值,我很难得到我正在使用的这个示例来实际打印正确的结果 我试着做: print "My name is {name} and my email is {email}".format(dict(name="Jeff", email="me@mail.com")) print "My name is {0} and my email is {1}".format(dict(name="Jeff", email="me@mail.com")) 而且它会错误地说
print "My name is {name} and my email is {email}".format(dict(name="Jeff", email="me@mail.com"))
print "My name is {0} and my email is {1}".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 {name} and my email is {email}".format(dict(name="Jeff", email="me@mail.com"))
print "My name is {0} and my email is {1}".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
>>>
以下是有关的语法参考。只需删除对
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
您缺少[]
(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
谢谢因此,您不必使用dict?@user3079411-不,不必使用str.format
。如果你有一本字典,你可以像@hwnd那样索引它。但是在你的情况下,对dict的调用是不必要的。哦,好吧,我现在明白了。非常感谢。因此,您不必使用dict?@user3079411-不,不必使用str.format
。如果你有一本字典,你可以像@hwnd那样索引它。但是在你的情况下,对dict的调用是不必要的。哦,好吧,我现在明白了。非常感谢。谢谢你的回复。谢谢你的回复。