user3079411
user3079411

Reputation: 55

String interpolation working with python

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

Answers (2)

hwnd
hwnd

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

user2555451
user2555451

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

Related Questions