Python named string format arguments

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

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

Similarly '{name} and {state}'.format(name='X', state='Y')printsX and Y

But why does this not work?

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

He is typing "Hi! My name is {name}. I live in {state}"

+4
source share
1 answer

formatDoesn't change the line you call it to; it returns a new line. 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.

+6
source

Source: https://habr.com/ru/post/1649040/


All Articles