Buffalo Hunter
Buffalo Hunter

Reputation: 103

Named string format arguments in Python

I am using Python 2.x, and trying to understand the logic of string formatting using named arguments. I understand:

"{} and {}".format(10, 20) prints '10 and 20'.

In like manner '{name} and {state}'.format(name='X', state='Y') prints X and Y

But why this isn't working?

my_string = "Hi! My name is {name}. I live in {state}"
my_string.format(name='Xi', state='Xo')
print(my_string)

It prints "Hi! My name is {name}. I live in {state}"

Upvotes: 5

Views: 965

Answers (1)

khelwood
khelwood

Reputation: 59229

format doesn't alter the string you call it on; it returns a new string. If you do

my_string = "Hi! My name is {name}. I live in {state}"
new_string = my_string.format(name='Xi', state='Xo')
print(new_string)

then you should see the expected result.

Upvotes: 9

Related Questions