Python Multiple updates , Also introduced a variety of syntax for formatting strings .
python2.6 Before the release , Use % The format string follows C The output format of language .
name='xiaoming'
age=12
print("My name is %s,My age is %d" %(name,age))
# Output :My name is xiaoming,My age is 12
comment : Too much % It seems that the code is a little messy .
format yes python2.6 A new way to format strings , comparison % The format method has the following advantages :
- A single parameter can be output multiple times , The order of parameters can be different
- The filling method is very flexible , Alignment is very powerful
- It's officially recommended
Instructions :
print("...{ Indexes }, ... , { Indexes }, ...".format( value 1, value 2))
# Indexes {} It's empty , The default value is in order
print("...{key1}, ... , {key2}, ...".format(key1=value,key2=value))
name='xiaoming'
age=12
print('My name is {}, My age is {}'.format(name,age))
print('My name is {0}, My age is {1}'.format(name,age))
print('My name is {name}, My age is {age}'.format(name='xiaoming',age=12))
# Output :My name is xiaoming,My age is 12
comment : Finally, it is not necessary to correspond one by one in order , You can specify the name and value of the placeholder . Don't bother to remember %s %d %f That's it .
# First fetch value , Then set the fill format after the colon :{ Indexes :[ Fill character ][ Alignment mode ][ Width ]}
# *<20: Align left , in total 20 Characters , Not enough * Fill in
print('{0:*<20}'.format('hellopython'))
# *>20: Right alignment , in total 20 Characters , Not enough * Fill in
print('{0:*>20}'.format('hellopython'))
# *^20: centered , in total 20 Characters , Not enough * Fill in
print('{0:*^20}'.format('hellopython'))
Output :
hellopython*********
*********hellopython
****hellopython*****
# Retain 2 Significant digits
print("{:.2f}".format(3.1415926))
# Convert to binary
print('{0:b}'.format(16))
# Convert to octal
print('{0:o}'.format(10))
# Convert to hex
print('{0:x}'.format(15))
Output
3.14
10000
12
f
stay Python 3.6 Introduction in 了 f-strings, Not only is better than str.format Easy to use , And more efficient . Be careful :Python3.6 And later versions can use this syntax .
Instructions :
f-string It's a string preceded by "f",{} Use variables directly 、 Expression etc. .
name='xiaoming'
age=12
#{} Use variables directly in
print(f'My name is {name},My age is {age}')
#{} Run the expression in
print(f'{1+2+3}')
# call Python Built in functions
print(f'{name.upper()}')
# use lambda Anonymous functions : You can do complex numerical calculations
fun = lambda x : x+1
print(f'{fun(age)}')
# Output
My name is xiaoming,My age is 12
6
XIAOMING
13
comment : somewhat JSP EL The expression smells like that .