python basis - three main ways to format output

Placeholder

Often, there is a scene in the program: the user to enter information into a fixed format and printing

Such as requiring the user to enter a user name and age, and then print the following format: My name is xxx, my age is xxx.

Obviously, a character string with a comma splice, the user can input the name and age into the end, not placed in the specified location xxx, and the figure must also be str (digital) conversion to string splicing, very the trouble, we have to try.

+ Method (using too little scene -> most cases younger brother usage)

Carried out a string with a comma splice, the user can input the name and age into the end, not placed in the specified location xxx, and the figure must also be str (digital) conversion to string splicing, very troublesome
Code as follows

age = 18
print('My name is nash,my age is '+str(age))
# 输出结果 ---> My name is xxx,my age is 18

To use multi-string +

name = 'nash'
age = 18
print('My name is '+name+' my age is '+str(age))
# 输出结果 ---> My name is nick my age is 18

The method of using the ever more awkward above, more and more cumbersome. Which need to use placeholders, such as:% s (for all data types),% d (only for the number types) -> personal views that use time travel the world% s

name = 'nash'
age = 18
print('my name is %s my age is %s' % (name, age))
# my name is nash my age is 18
age = 18
print('my age is %d' % age)
# my age is 18


format format

Speaking really, very sad way to format if you need to use this encounter multi-parameter time, or need to pass on a lot of parameters crackling behind the sentence. This is better to use with placeholders or below f-String Format.
ps: turtle t before they recommended, personally feel is best to use a third now

name = 'nash'
age = 18
print("Hello, {}. You are {}.".format(name, age))
# Hello, nash. You are 19.
name = 'nash'
age = 18
print("Hello, {1}. You are {0} years old.".format(age, name))
# Hello, nash. You are 18 years old.
name = 'nash'
age = 18
print("Hello, {name}. You are {age} years old.".format(age=age, name=name))
# Hello, nash. You are 18 years old.


f-String formatting

Compare placeholder way, python3.6 version adds f-String formatted way, relatively simple to understand. This is recommended.

name = "nash"
age = 18
print(f"Hello, {name}. You are {age}.")
# Hello, nash. You are 19.

Uppercase F apply.

name = "nash"
age = 18
print(F"Hello, {name}. You are {age}.")
# 输出结果
# Hello, nash. You are 18.

After performing multiplication variable format (i.e., after the end of the operation, formatted as the final step)

age = 18
print(f'{age*2}')
# 输出结果
# 36

Other places to see a show of operation (f interior is not external influences, and can also floating point decimal values)

salary = 6.6666
print(f'{salary:.2f}')
6.67

Guess you like

Origin www.cnblogs.com/suren-apan/p/11374636.html