5

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}"

1 Answer 1

9

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.

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

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.