使用python的字符串插值

2024-04-23 12:09:33 发布

您现在位置: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

谢谢。你知道吗


Tags: and字符串namecomformatisemailmy
2条回答

只需删除对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语法的参考。你知道吗

缺少[]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

相关问题 更多 >