Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 269
Buffalo Hunter Avatar asked Jul 25 '16 13:07

Buffalo Hunter


People also ask

What is the string format method in Python?

The format() method formats the specified value(s) and insert them inside the string's placeholder. The placeholder is defined using curly brackets: {}. Read more about the placeholders in the Placeholder section below. The format() method returns the formatted string.

What does __ format __ do in Python?

The __format__ method is responsible for interpreting the format specifier, formatting the value, and returning the resulting string. It is safe to call this function with a value of “None” (because the “None” value in Python is an object and can have methods.)

How do you use %s in Python?

The %s operator is put where the string is to be specified. The number of values you want to append to a string should be equivalent to the number specified in parentheses after the % operator at the end of the string value. The following Python code illustrates the way of performing string formatting.

What is string format operator explain with examples?

Python String format() is a function used to replace, substitute, or convert the string with placeholders with valid values in the final string. It is a built-in function of the Python string class, which returns the formatted string as an output. The placeholders inside the string are defined in curly brackets.


1 Answers

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.

like image 154
khelwood Avatar answered Oct 27 '22 20:10

khelwood