Three ways formatted output
A 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, the 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) converter to perform with string concatenation, very troublesome, let's give it a try.
>>> age = 19
>>> print('My name is xxx,my age is '+str(age))
...My name is xxx,my age is 19
>>> age = 19
>>> print('My name is xxx,my age is', age)
...My name is xxx,my age is 19
>>> name = 'reed'
>>> age = 19
>>> print('My name is '+name+' my age is '+str(age))
...My name is reed my age is 19
The method of using the ever more awkward above, more and more cumbersome. Which requires use of a placeholder, such as:% s (for all data types),% d (only for the number types)
>>> name = 'reed'
>>> age = 19
>>> print('my name is %s my age is %s' % (name, age))
...my name is reed my age is 19
>>> age = 19
>>> print('my age is %d' % age)
...my age is 19
Two, 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.
>>> name = 'nick'
>>> age = 19
>>> print("Hello, {}. You are {}.".format(name, age))
...Hello, nick. You are 19.
>>> print("Hello, {1}. You are {0}-{0}.".format(age, name))
...Hello, nick. You are 19-19.
>>>print("Hello, {name}. You are {age}-{age}.".format(age=age, name=name))
...Hello, nick. You are 19-19.
Three, f-String Format
Compared placeholder way, python3.6 version adds f-String formatted way, relatively simple to understand, this is the way I use the most, it is recommended to use this way.
>>> name = "nick"
>>> age = 19
>>> print(f"Hello, {name}. You are {age}.")
...Hello, nick. You are 19.
#大写的F也适用。
>>> print(F"Hello, {name}. You are {age}.")
...Hello, nick. You are 19.
>>> print(f'{age*2}')
...38
#再给你秀个以后可能会用到的操作。
>>> salary = 6.6666
>>> print(f'{salary:.2f}')#保留两位小数,按四舍五入
...6.67