Python supports string formatting, which you might use when you need to iterate and change a particular part of a string, or when you’re dealing with a very complex expression, inserting a variable into a string.

In your program, you see operators like %s, %d, that’s what string formatting is in Python, and you call the string format method, which is one way of formatting strings in Python.

Using formatting symbols (PYTHon2.x and PYTHon3.x)

Common formatting symbols are as follows:

Formatting symbol meaning
%s Format using the STR () string conversion
%d A signed decimal integer
%f Floating point number

use

name = 'xiao li'
print('My name is %s'%name)
age = 27
print('This year %d years old'%age)
height = 1.75
print('Height % F m'%height)
Limit the number of decimal places to be retained in the output floating-point number
print('Height %.2f meters'%height)
Copy the code

The output

My name is Xiao Li this year27At the age of the height1.750000M height1.75meterCopy the code

Format () Formats output (python3.x)

Replace the traditional % with {} to format the output, eliminating the need to format the character format

name = 'xiao li'
print('My name is {}'.format(name))
age = 27
print('I am {} years old.'.format(age))
height = 1.75
print('Height {} m'.format(height))
Limit the number of decimal places to be retained in the output floating-point number
print('Height {:.3f} m'.format(height))
# can output according to the index position
print('Numbers {1}{2} and {0}'.format("123".456.'789'))
# has two levels of braces, and output results with only one level of braces
print('Numbers {{{1}{2}}} and {0}'.format("123".456.'789'))
# Allow an argument to be used twice
print('{1} {0} {1}' age.format('xiao li'.27))
# can be used by adding keyword arguments
print('{name} {the age},.format(age=27,name='xiao li'))Copy the code

The output

My name is Xiao Li this year27At the age of the height1.75M height1.750M number456789and123Digital {456789} and123
27Xiao li27At the age of xiao li27At the age ofCopy the code

F-string New features introduced in the new version

At the most basic level, we simply prefix the string with f, and insert the variable into the {} of the string

name = 'xiao li'
print(F 'my name is{name}')
Copy the code

This new f-string feature makes our code much cleaner and more readable. It is also nice to use it for concatenating SQL statements and other things.

For details about the new f-String features, see the following link f-String New Features