Reputation: 55
I am new to learning how to use string interpolation in strings and am having trouble getting this example I am working with to actual print the right results.
I've tried to do:
print "My name is {name} and my email is {email}".format(dict(name="Jeff", email="[email protected]"))
And it errors saying KeyError: 'name'
Then I tried using:
print "My name is {0} and my email is {0}".format(dict(name="Jeff", email="[email protected]"))
And it prints
My name is {'email': '[email protected]', 'name': 'Jeff'} and my email is {'email': '[email protected]', 'name': 'Jeff'}
So then I tried to do:
print "My name is {0} and my email is {1}".format(dict(name="Jeff", email="[email protected]"))
And it errors saying IndexError: tuple index out of range
It should give me the following output result back:
My name is Jeff and my email is [email protected]
Thanks.
Upvotes: 1
Views: 76
Reputation: 70732
You're missing the []
(getitem
) operator.
>>> print "My name is {0[name]} and my email is {0[email]}".format(dict(name="Jeff", email="[email protected]"))
My name is Jeff and my email is [email protected]
Or use it without calling 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]
Upvotes: 3
Reputation:
Just remove the call to 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]
>>>
Here is a reference on the syntax for string formatting.
Upvotes: 8