1

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.

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. So you don't have to use dict?
@user3079411 - No, not with str.format. If you have a dictionary though, you can index it like @hwnd demonstrated. But in your case, the call to dict is unnecessary.
3

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.