程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

6.1_ 6 Python3. X introduction P6 [string formatting] four methods (manual,%-formatting, str.format (), f-string)

編輯:Python

Related links

  • Catalog
  • Mac M1 Python Environment building
  • Python3.x introduction P1 【 Basics 】 notes 、 identifier 、 Variable 、 data type
  • Python3.x introduction P2 【 Basics 】 Operator
  • Python3.x introduction P3 【 Basics 】 Process statement 【 Loop structure 】
  • Python3.x introduction P4 【 Basics 】 Variable sequence ( list list、 Dictionaries dict、 aggregate set)
  • Python3.x introduction P5 【 Basics 】 Immutable sequence ( Tuples tuple、 character string str)
  • Python3.x introduction P6 【 String formatting 】 Four ways ( Manual 、%-formatting、str.format()、f-String)
  • Python3.x introduction P7 【 function 】

One 、 String formatting

  • Purpose : More beautiful output format
  • edition :3.8.9( The test results of different versions may be different )

1.1 Format initial experience

1) Manual Manual String Formatting. The effect of this method is limited , Generally, you can only do simple format processing . This method will not be described in detail later .

 Align by the following method
center(): Align center , The first 1 Two parameters specify the width , The first 2 A parameter specifies the filler , The first 2 Two parameters are optional , Default is space , If the set width is less than the actual width, the original string is returned
ljust(): Align left , The first 1 Two parameters specify the width , The first 2 A parameter specifies the filler , The first 2 Two parameters are optional , Default is space , If the set width is less than the actual width, the original string is returned
rjust(): Right alignment , The first 1 Two parameters specify the width , The first 2 A parameter specifies the filler , The first 2 Two parameters are optional , Default is space , If the set width is less than the actual width, the original string is returned
zfill(): Right alignment , Use... On the left 0 fill , The first 1 Two parameters specify the width , If the set width is less than the actual width, the original string is returned
Case study
# Align format output 
for x in range(1, 11):
print(str(x).rjust(2), str(x * x).rjust(3), end=' ')
# Note use of 'end' on previous line
print(str(x * x * x).rjust(4))
''' 1 1 1 2 4 8 3 9 27 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 729 10 100 1000 '''

2) %-formattingOld string formatting. This method has been used in Python In language .
Its effect is similar to that in C Used in language %format % values%sprintf(). Some historical relics bug As a result, tuples may not be displayed correctly (tuples) And the dictionary (dictionaries), It is recommended to use... In the official documents str.format() .

Case study
# 1. Sequential positioning 
print('%s has %03d quote types.' % ('Python', 2)) # Python has 002 quote types.
# 2. Key parameters 
print('%(language)s has %(number)03d quote types.' %
{
'language': "Python", "number": 2}) # Python has 002 quote types.

3) str.format()The String format() method. This method starts from Python2.6 Start introducing . Can be in Python Official update log Medium PEP3101 find str.format() Detailed usage .str.format() It's right %-formatting Improvement . It uses normal function call syntax , And can be converted to a string through the... On the object being converted to a string format() Method to extend .

Case study
""" @author GroupiesM @date 2022/6/28 16:27 @introduction """
# 1. Sequential positioning 
print(1, 'We are the {} who say "{}!"'.format('knights', 'Ni')) # We are the knights who say "Ni!"
# 2. Digital positioning 
print(2, '{0} and {1}'.format('spam', 'eggs')) # spam and eggs
print(2, '{1} and {0}'.format('spam', 'eggs')) # eggs and spam
# 3. Key parameters 
print(3, 'This {food} is {adjective}.'.format(
food='spam', adjective='absolutely horrible')) # This spam is absolutely horrible.
# 4. Digital positioning + Key parameters 
print(4, 'The story of {0}, {1}, and {other}.'.format(
'Bill', 'Manfred', other='Georg')) # The story of Bill, Manfred, and Georg.
# 5. Split the dictionary 
table = {
'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
print(5, 'Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; ''Dcab: {0[Dcab]:d}'
.format(table)) # Jack: 4098; Sjoerd: 4127; Dcab: 8637678
# 6. Unzip the dictionary 
table = {
'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
print(6, 'Jack: {Jack}; Sjoerd: {Sjoerd}; Dcab: {Dcab}'
.format(**table)) # Jack: 4098; Sjoerd: 4127; Dcab: 8637678
# 7. Unzip the dictionary ( Specify the type )
table = {
'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
print(7, 'Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'
.format(**table)) # Jack: 4098; Sjoerd: 4127; Dcab: 8637678
# 8. Split the list 
lst = [4127, 4098, 8637678]
print(8, 'Jack: {0[1]:d}; Sjoerd: {0[0]:d}; ''Dcab: {0[2]:d}'
.format(lst)) # Jack: 4098; Sjoerd: 4127; Dcab: 8637678
# 9. Unzip the list ( Default sort )
lst = [4127, 4098, 8637678]
print(9, 'Jack: {}; Sjoerd: {}; ''Dcab: {}'
.format(*lst)) # Jack: 4127; Sjoerd: 4098; Dcab: 8637678
# 10. Unzip the list ( Specified sorting )
lst = [4127, 4098, 8637678]
print(10, 'Jack: {1}; Sjoerd: {0}; ''Dcab: {2}'
.format(*lst)) # Jack: 4098; Sjoerd: 4127; Dcab: 8637678
# 11. Unzip the collection ( Default sort )
st = {
4127, 4098, 8637678}
print(11, 'Jack: {}; Sjoerd: {}; ''Dcab: {}'
.format(*st)) # Jack: 4127; Sjoerd: 4098; Dcab: 8637678
# 12. Unzip the collection ( Specified sorting )
st = {
4127, 4098, 8637678}
print(12, 'Jack: {1}; Sjoerd: {0}; ''Dcab: {2}'
.format(*st)) # Jack: 4098; Sjoerd: 4127; Dcab: 8637678
# 13. Split tuple 
tup = (4127, 4098, 8637678)
print(13, 'Jack: {0[1]:d}; Sjoerd: {0[0]:d}; ''Dcab: {0[2]:d}'
.format(tup)) # Jack: 4098; Sjoerd: 4127; Dcab: 8637678
# 14. Decompress tuples ( Default sort )
tup = (4127, 4098, 8637678)
print(14, 'Jack: {}; Sjoerd: {}; ''Dcab: {}'
.format(*tup)) # Jack: 4127; Sjoerd: 4098; Dcab: 8637678
# 15. Decompress tuples ( Specified sorting )
tup = (4127, 4098, 8637678)
print(14, 'Jack: {1}; Sjoerd: {0}; ''Dcab: {2}'
.format(*tup)) # Jack: 4098; Sjoerd: 4127; Dcab: 8637678
# 16. Traversal formatting 
for x in range(1, 11):
print(15, '{0:2d} {1:3d} {2:4d}'.format(x, x * x, x * x * x))
''' 1 1 1 2 4 8 3 9 27 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 729 10 100 1000 '''

4) f-StringFormatted String Literalsf-String Refers to the direct use of... In a string Python Variable , You need to add... Before the string f or F mark . This method is more flexible for data processing , You can even substitute variables into functions , Output results .

Case study
# 1. 3.8 New characteristics 
name, score = ' Zhang San ', 45.6
print(f'name={
name}, score={
score:.3f}') # Python3.6 name= Zhang San , score=45.600
print(f'{
name=}, {
score=:.3f}') # Python3.8 name=' Zhang San ', score=45.600
# 2.pi Keep three decimal places 
import math
print(f'The value of pi is approximately {
math.pi:.3f}.') # The value of pi is approximately 3.142.
# 3. Column alignment 
table = {
'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
for name, phone in table.items():
print(f'{
name:10} ==> {
phone:10d}')
''' Sjoerd ==> 4127 Jack ==> 4098 Dcab ==> 7678 '''
# 4. format conversion 【ascii()=!a】、【str()=!s】、【repr=!r】
animals = 'eels'
print(f'My hovercraft is full of {
animals}.') # My hovercraft is full of eels.
print(f'My hovercraft is full of {
animals!r}.') # My hovercraft is full of 'eels'.
# 5. Nested calculation name=' Zhang San ', (height+2)=182.40
name, age, height = ' Zhang San ', 20, 180.4
print(f'{
name=}, {
(height+2)=:.2f}')
# 6. Nested function name=' Zhang San ', sum(height,3)=183.40
name, age, height = ' Zhang San ', 20, 180.4
def sum(a, b):
return a + b
print(f'{
name=}, {
sum(height,3)=:.2f}')

1.2 Python Official documents

Baidu can't find clear information , Or ambiguous , All in official documents + Local test results shall prevail :
The Python Tutorial-Python course

Fancier Output Formatting- More beautiful output format


1.3 Format specification Mini language

About Format Specification Mini-Language, Its format is in str.format() as well as f-String It is similar to the general , But there are also some subtle differences . This part is extracted from official documents , Translation only .

 Grammar tree format_spec ::= [[fill]align][sign][#][0][width][grouping_option][.precision][type]
Infill fill ::= <any character>
Alignment mode align ::= "<" | ">" | "=" | "^"
Symbol options sign ::= "+" | "-" | " "
Total length width ::= digit+
Grouping options grouping_option ::= "_" | ","
Significant figures precision ::= digit+
data type type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
align- Alignment mode Options meaning ‘<’ Force fields to align left in free space ( This is the default setting for most objects ).‘>’ Force fields to align right in free space ( This is the default value for numbers ).‘=’ Force padding on symbols ( If there is ) after , But before the numbers . This is used for printing in the format “+000000120” Field of .
This alignment option is only valid for numeric types . When “0” Immediately before the field width , It will be the default .‘^’ Force the field to be centered within the available space .sign- Symbol options The symbol option is only valid for numeric types , And it can be one of the following options : Options meaning ‘+’ Means to add... Before a positive number ’+‘, Add... Before negative numbers ’-'.‘-’ Indicates that a positive number is not added , Add... Before negative numbers ’-'( The default option ). No Means to add... Before a positive number ’ ‘, Add... Before negative numbers ’-'.type- data type

1. Character

Options meaning function ‘s’ String format .( The default option )str() No And ’s’ identical .

2. Integer type (%-formatting Parameter... Is not supported b,%-formatting Parameters are not supported )

Options meaning function ‘b’ Binary format . Output to 2 Is the number of the cardinal number .bin()‘c’ character . Convert integers to corresponding before printing unicode character .chr()‘d’ Decimal integer . Output to 10 Is the number of the cardinal number .‘o’ Octal format . Output to 8 Is the number of the cardinal number .oct()‘x’ Hexadecimal format . Output to 16 Is the number of the cardinal number , Yes 9 The above numbers are in lowercase letters .hex()‘X’ Hexadecimal format . Output to 16 Is the number of the cardinal number , Yes 9 The above numbers use capital letters .hex()‘n’ And ’d’ identical . No And ’d’ identical .

3. floating-point

Options meaning function ‘e’ Scientific notation . For a given accuracy , Format numbers with scientific notation , Use letters “e” Separate the coefficient from the index .
The coefficient has one digit before the decimal point , There is a digit after the decimal point , There is one significant figure in total .
In the absence of precision , Use the precision of the number after the decimal point as a floating-point number , And display all coefficient numbers in decimal system .
If there is no number after the decimal point , Unless you use this option , Otherwise, the decimal point will be deleted .‘E’ And ’e’ identical , But with letters "E" Separate the coefficient from the index .‘f’ Fixed point representation . The integer 、 Convert floating-point numbers to floating-point numbers . As specified percision Keep decimals , If no default reservation is specified 6 Decimal place .‘F’ And ’f’ identical . The difference is that ’f’ :nan( An infinitesimal ),inf( infinity ),‘F’ :NAN( An infinitesimal ),INF( infinity ).‘g’ General format . Auto adjust will be integer 、 Convert to floating point Floating point or scientific notation .‘G’ And ’g’ identical . Different reference ’e’ And ’E’, and ’f’ And ’F’‘n’ And ’g’ identical .‘%’ percentage . Multiply the number by 100, Add a percent sign , Default hold 6 Decimal place No And ’d’ identical .

1.4 Syntax example

1. %-formatting

""" Format 1 : 1. One parameter :print(' My name is %s' % name) # Brackets can be omitted 2. Multiple parameters :print(' My name is %s, This year, %d year ' % (name, age)) """
name, age, height = ' Zhang San ', 20, 180.4
print('%s' % name) # Zhang San 
print('%s--%f' % (name, height)) # Zhang San --180.400000
""" Format two : 1. One parameter :print('%(name)s' % {'name': ' Zhang San '}) 2. Multiple parameters :print('%(name)s--%(age)d' % {'name': ' Zhang San ', 'age': 18}) """
name, age, height = ' Zhang San ', 20, 180.4
print('%(name)s' % {
'name': ' Zhang San '}) # Zhang San 
print('%(name)s--%(age)d' % {
'name': ' Zhang San ', 'age': 18}) # Zhang San --18

2. str.format()

""" Mode one : Specify the parameters """
'''1.1 Does not set the specified location , By default '''
name, age, height = ' Zhang San ', 20, 180.4
print(1.1, ' My name is {}, My name is {}, This year, {} year , height {}'.format(name, name, age, height, )) # My name is zhang SAN , My name is zhang SAN , This year, 20 year , height 180.4
'''1.2 Set the specified location '''
name, age, height = ' Zhang San ', 20, 180.4
print(1.2, ' My name is {0}, My name is {0}, This year, {1} year , height {2}'.format(name, age, height)) # My name is zhang SAN , My name is zhang SAN , This year, 20 year , height 180.4
'''1.3 Set parameters The websites : Novice tutorial , Address www.runoob.com '''
name, age, height = ' Zhang San ', 20, 180.4
print(1.3, ' The websites :{name}, Address {url}'.format(name=" Novice tutorial ", url="www.runoob.com"))
''' Mode two : Get by sequence '''
'''2.1 Through the dictionary dict Set parameters ( Unpack ) The websites : Novice tutorial , Address www.runoob.com '''
name, age, height = ' Zhang San ', 20, 180.4
site_dict = {
"name": " Novice tutorial ", "url": "www.runoob.com"}
print(2.1, " The websites :{name}, Address {url}".format(**site_dict)) # Use ** Unpacking operation 
'''2.2 Through the dictionary dict Set parameters ( No unpacking ) The websites : Novice tutorial , Address www.runoob.com '''
name, age, height = ' Zhang San ', 20, 180.4
site_dict = {
"name": " Novice tutorial ", "url": "www.runoob.com"}
print(2.2, " The websites :{0[name]}, Address {0[url]}".format(site_dict)) # "0" It's fixed writing Use [] Visit the dictionary 
'''2.3 Through the list list Index setting parameters The websites : Novice tutorial , Address www.runoob.com '''
name, age, height = ' Zhang San ', 20, 180.4
my_list = [' Novice tutorial ', 'www.runoob.com']
print(2.3, " The websites :{}, Address {}".format(*my_list)) # Use * Unpacking operation 
'''2.4 Through the list list Index setting parameters The websites : Novice tutorial , Address www.runoob.com '''
name, age, height = ' Zhang San ', 20, 180.4
my_list = [' Novice tutorial ', 'www.runoob.com']
print(2.4, " The websites :{0[0]}, Address {0[1]}".format(my_list)) # "0" It's written in a fixed way 

3. f-String

# A lowercase letter f
name, age, height = ' Zhang San ', 20, 180.4
print(f' My name is {
name}, My name is {
name}, This year, {
age} year , height {
height}') # My name is zhang SAN , My name is zhang SAN , This year, 20 year , height 180.4
# Capitalization F
name, age, height = ' Zhang San ', 20, 180.4
print(F' My name is {
name}, My name is {
name}, This year, {
age} year , height {
height}') # My name is zhang SAN , My name is zhang SAN , This year, 20 year , height 180.4

Two 、%-formatting

""" @author GroupiesM @date 2022/6/22 14:20 @introduction String formatting - The way 1 %【 Not recommended 】 1. brief introduction % No. format the string from Python It has existed since its birth . at present ,Python Officials have not abandoned this method , But it is not recommended . 2.% Formant grammar Grammar 1 :'${flags}%${width}${.percision}%${typecode}' % ${content} Grammar II :%(${name})${#}${flags}${width}${.precision}%${typecode} % ${
{'k1':v1,'k2':v2,...}} ${name} 【 Optional 】, Used to select the specified key ${#} 【 Optional 】 For octal (oct)、 Hexadecimal (hex), If you add #, Will be displayed 0o/0x, Otherwise it doesn't show ${flags} 【 Optional 】, Alignment mode 、 The sign , The values to choose from are :【+、-、 、0】 + Right alignment : The plus sign of a positive number , Plus minus sign of negative number - Align left : There is no minus sign before a positive number , Add a minus sign before a negative number Space Right alignment : Put a space before a positive number , Add a minus sign before a negative number ; 0 Right alignment : There is no sign before a positive number , Add a minus sign before a negative number ; use 0 Fill in the blanks ${width} 【 Optional 】, Total length ( Fill in the space with insufficient digits ) ${.precision} 【 Optional 】, Effective digits ${typecode} 【 Mandatory 】, data type 、 Format 1) Pass in " String type " Parameters of s, Get the incoming object str() Return value of method ( character string - For human reading ), And format it to the specified location r, Gets the value of the incoming object repr() Return value of method ( character string - For the interpreter ), And format it to the specified location blank , Type not specified , By default s 2) Pass in " Integer types " Parameters of c, Gets the value of the incoming object chr() Return value of method (unicode Corresponding value ),10 The base range is 0 <= i <=1114111 --% Format symbol : No, b(2 Hexadecimal Numbers ) Method ,format Formatting can support -- d,10 Hexadecimal integer o, Gets the value of the incoming object oct() Return value of method (8 Hexadecimal Numbers ), And format it to the specified location x, Gets the value of the incoming object hex() Return value of method (16 Hexadecimal Numbers ), And format it to the specified location ( English lowercase ) X, Gets the value of the incoming object hex() Return value of method (16 Hexadecimal Numbers ), And format it to the specified location ( In capital ) 3) Pass in " Floating point or decimal type " Parameters of e, The integer 、 Convert floating-point numbers to scientific counting , And format it to the specified location ( A lowercase letter e) E, The integer 、 Convert floating-point numbers to scientific counting , And format it to the specified location ( Capitalization E) f, The integer 、 Convert floating-point numbers to floating-point numbers , And format it to the specified location ( The decimal point is reserved by default 6 position ) F, ditto g, Auto adjust will be integer 、 Convert to floating point Floating point or scientific notation ( exceed 6 The number of digits is counted scientifically ), And format it to the specified location ( If it's a scientific count, it's e;) G, Auto adjust will be integer 、 Convert to floating point Floating point or scientific notation ( exceed 6 The number of digits is counted scientifically ), And format it to the specified location ( If it's a scientific count, it's E;) %, Multiply the number by 100, Add a percent sign , Default hold 6 Decimal place . When there is a format flag in the string , Need to use %% Represents a percent sign . ${content} 【 Mandatory 】, Content to format """
''' Complete syntax example 1: -16.9 1) ${flag} = '0' Right alignment : There is no sign before a positive number , Add a minus sign before a negative number ; use 0 Fill in the blanks 2) ${width} = '10' Total length ( Fill in the space with insufficient digits ) 3) ${precision} = '5, Effective digits 4) ${typecode} = 'f',' data type float '''
print('%(money)#010.5f' % {
'money': -16.9})# -016.90000
''' Complete syntax example 2: 100 1) ${flag} = '+' Right alignment : The plus sign of a positive number , Plus minus sign of negative number 2) ${#} = '#' For binary (bin)、 octal (oct)、 Hexadecimal (hex), If you add #, Will be displayed 0b/0o/0x, Otherwise it doesn't show 3) ${width} = '10' Total length ( Fill in the space with insufficient digits ) 4) ${precision} = '5', Effective digits 5) ${typecode} = 'f', data type float '''
print('%(money)#+10d' % {
'money': 100}) # +0o00144

2.1 【flags】 Alignment mode 、 The sign

""" @author GroupiesM @date 2022/6/23 16:26 @introduction 2.% Formant grammar Grammar 1 :'${flags}%${width}${.percision}%${typecode}' % ${content} Grammar II :%(${name})${#}${flags}${width}${.precision}%${typecode} % ${
{'k1':v1,'k2':v2,...}} """
name, age, money, height = ' Zhang San ', 20, -20, 180.4
''' Alignment mode 、 The sign ${flags}:【 Optional 】 No Right alignment : Put a space before a positive number , Add a minus sign before a negative number + Right alignment : The plus sign of a positive number , Plus minus sign of negative number - Align left : There is no minus sign before a positive number , Add a minus sign before a negative number Space Right alignment : Put a space before a positive number , Add a minus sign before a negative number 0 Right alignment : There is no sign before a positive number , Add a minus sign before a negative number ; use 0 Fill in the blanks P.S 1. Only when ${width}> Content length , Alignment is effective 2. Different ${typecode} Will affect the alignment , The following for s character string 、d Integers 、f floating-point Three types of tests '''
print('----s character string ----')
print(1, '%10s' % name)
print(2, '%+10s' % name)
print(3, '%-10s' % name)
print(4, '% 10s' % name)
print(5, '%010s' % name)
''' 1 Zhang San 2 Zhang San 3 Zhang San 4 Zhang San 5 Zhang San '''
print('----d Integers ----')
print(1, '%10d' % money)
print(2, '%+10d' % money)
print(3, '%-10d' % money)
print(4, '% 10d' % money)
print(5, '%010d' % money)
''' 1 -20 2 -20 3 -20 4 -20 5 -000000020 '''
print('----f floating-point ----')
print(1, '%15f' % height)
print(2, '%+15f' % height)
print(3, '%-15f' % height)
print(4, '% 15f' % height)
print(5, '%015f' % height)
''' 1 180.400000 2 +180.400000 3 180.400000 4 180.400000 5 00000180.400000 '''

2.2 【width】 Total length

""" @author GroupiesM @date 2022/6/23 16:26 @introduction 2.% Formant grammar Grammar 1 :'${flags}%${width}${.percision}%${typecode}' % ${content} Grammar II :%(${name})${#}${flags}${width}${.precision}%${typecode} % ${
{'k1':v1,'k2':v2,...}} """
name, age, money, height = ' Zhang San ', 20, -20, 180.4
''' Total length ${width}:【 Optional 】 %s Do not specify length %1s ${width} < Character length , Don't take effect %2s ${width} = Character length , Don't take effect %10 ${width} > Character length , take effect '''
print('%s' % name)
print('%1s' % name)
print('%2s' % name)
print('%10s' % name)
''' Zhang San Zhang San Zhang San Zhang San '''

2.3 【percision】 Effective digits

""" @author GroupiesM @date 2022/6/23 16:26 @introduction 2.% Formant grammar Grammar 1 :'${flags}%${width}${.percision}%${typecode}' % ${content} Grammar II :%(${name})${#}${flags}${width}${.precision}%${typecode} % ${
{'k1':v1,'k2':v2,...}} """
name, age, money, height = ' Zhang San ', 20, -20, 180.4
''' Effective digits ${.precision}:【 Optional 】 1. character string :' Zhang San ',${.precision} Will intercept the string %s Don't specify ${precision} %.1s ${.precision} < Character length , Cut from left to right 1 position ' Zhang ' %.2s ${.precision} = Character length , Don't take effect %.10 ${.precision} > Character length , Don't take effect 2. Integers :'23',${.precision} The part exceeding the length shall be filled in the front 0 %d Don't specify ${precision} %.1d ${.precision} < Integer length , Don't take effect %.2d ${.precision} = Integer length , Don't take effect %.10 ${.precision} > Integer length , The excess part is supplemented in the front 0 3. floating-point '180.45',${precision} Indicates the number of significant digits ( Floating point type means : Number of decimal places ), Default ${precision}=6 %f Don't specify ${precision}, Retain 6 Decimal place '180.450000' %.1f ${.precision} < Character length , Retain 1 Decimal place '180.4' %.2f ${.precision} = Character length , Retain 2 Decimal place '180.45' %.15f ${.precision} > Character length , Retain 15 Decimal place '180.449999999999989' '''
print('----s character string ----')
print(1, '%s' % name)
print(2, '%.1s' % name)
print(3, '%.2s' % name)
print(4, '%.10s' % name)
''' 1 Zhang San 2 Zhang 3 Zhang San 4 Zhang San '''
print('----s character string ( Specify the length )----')
print(1, '%10s' % name)
print(2, '%10.1s' % name)
print(3, '%10.2s' % name)
print(4, '%10.10s' % name)
''' 1 Zhang San 2 Zhang 3 Zhang San 4 Zhang San '''
print('----d Integers ----')
print(1, '%d' % age)
print(2, '%.1d' % age)
print(3, '%.2d' % age)
print(4, '%.5d' % age)
''' 1 23 2 23 3 23 4 00023 '''
print('----d Integers ( Specify the length )----')
print(1, '%10d' % age)
print(2, '%10.1d' % age)
print(3, '%10.2d' % age)
print(4, '%10.5d' % age)
''' 1 23 2 23 3 23 4 00023 '''
print('----f floating-point ----') # Floating point type is calculated according to the number of digits after the decimal point 
print(1, '%f' % height) # Floating point type does not specify The decimal point is reserved by default 6 position 
print(2, '%.1f' % height)
print(3, '%.2f' % height)
print(4, '%.15f' % height)
''' 1 180.400000 2 180.4 3 180.40 4 180.400000000000006 '''
print('----f floating-point ( Specify the length )----')
print(1, '%10f' % height) # Floating point type does not specify The decimal point is reserved by default 6 position 
print(2, '%10.1f' % height)
print(3, '%10.2f' % height)
print(4, '%10.15f' % height)
''' 1 180.400000 2 180.4 3 180.40 4 180.400000000000006 '''

2.4 【typecode】 data type

""" @author GroupiesM @date 2022/6/23 16:26 @introduction 2.% Formant grammar Grammar 1 :'${flags}%${width}${.percision}%${typecode}' % ${content} Grammar II :%(${name})${#}${flags}${width}${.precision}%${typecode} % ${
{'k1':v1,'k2':v2,...}} ${typecode} 【 Mandatory 】, data type 、 Format 1) Pass in " String type " Parameters of s, Get the incoming object str() Return value of method ( character string - For human reading ), And format it to the specified location r, Gets the value of the incoming object repr() Return value of method ( character string - For the interpreter ), And format it to the specified location blank , Type not specified , By default s 2) Pass in " Integer types " Parameters of c, Gets the value of the incoming object chr() Return value of method (unicode Corresponding value ),10 The base range is 0 <= i <=1114111 --% Format symbol : No, b(2 Hexadecimal Numbers ) Method ,format Formatting can support -- d,10 Hexadecimal integer o, Gets the value of the incoming object oct() Return value of method (8 Hexadecimal Numbers ), And format it to the specified location x, Gets the value of the incoming object hex() Return value of method (16 Hexadecimal Numbers ), And format it to the specified location ( English lowercase ) X, Gets the value of the incoming object hex() Return value of method (16 Hexadecimal Numbers ), And format it to the specified location ( In capital ) 3) Pass in " Floating point or decimal type " Parameters of e, The integer 、 Convert floating-point numbers to scientific counting , And format it to the specified location ( A lowercase letter e) E, The integer 、 Convert floating-point numbers to scientific counting , And format it to the specified location ( Capitalization E) f, The integer 、 Convert floating-point numbers to floating-point numbers , And format it to the specified location ( The decimal point is reserved by default 6 position ) F, ditto g, Auto adjust will be integer 、 Convert to floating point Floating point or scientific notation ( exceed 6 The number of digits is counted scientifically ), And format it to the specified location ( If it's a scientific count, it's e;) G, Auto adjust will be integer 、 Convert to floating point Floating point or scientific notation ( exceed 6 The number of digits is counted scientifically ), And format it to the specified location ( If it's a scientific count, it's E;) %, When there is a format flag in the string , Need to use %% Represents a percent sign """
name, age, money, height = ' Zhang San ', ord('🫡'), -20, 180.4
''' data type ${typecode}:【 Mandatory 】( Not all parameters tested ) c, Gets the value of the incoming object chr() Return value of method (unicode Corresponding value ),10 The base range is 0 <= i <=1114111 o, Gets the value of the incoming object oct() Return value of method (8 Hexadecimal Numbers ), And format it to the specified location x, Gets the value of the incoming object hex() Return value of method (16 Hexadecimal Numbers ), And format it to the specified location '''
''' Parameters c -> obtain unicode'''
# obtain 🫡 Of unicode value : ord('🫡') -> 129761
print('c_1',chr(age)) # 🫡
print('c_2','%c' % age) # 🫡
''' Parameters o -> 8 Base number '''
print('o_1', oct(age)) # 0o375341
print('o_2', '%o' % age) # 375341
''' Parameters x -> 16 Base number '''
print('x_1', hex(age)) # 0x1fae1
print('x_2', '%x' % age) # 1fae1

2.5 【#】8、16 Hexadecimal symbol

""" @author GroupiesM @date 2022/6/23 16:26 @introduction 2.% Formant grammar Grammar 1 :'${flags}%${width}${.percision}%${typecode}' % ${content} Grammar II :%(${name})${#}${flags}${width}${.precision}%${typecode} % ${
{'k1':v1,'k2':v2,...}} ${#} 【 Optional 】 For octal (oct)、 Hexadecimal (hex), If you add #, Will be displayed 0o/0x, Otherwise it doesn't show """
name, age, money, height = ' Zhang San ', ord('🫡'), -20, 180.4
''' 8,16 Hexadecimal symbol ${#}:【 Optional 】 P.S 1. Only on ${typecode} in [o,x,X] Effective when , But no error will be reported in other cases '''
''' Parameters o -> 8 Base number '''
print('8_1', oct(age)) # 0o375341
print('8_2', '%#o' % age) # 0o375341
print('8-3', '%o' % age) # 375341
''' Parameters x -> 16 Base number '''
print('16_1', hex(age)) # 0x1fae1
print('16_3', '%#x' % age) # 0x1fae1
print('16_2', '%x' % age) # 1fae1

3、 ... and 、str.format()

For more details, please refer to :str.Format() grammar - Official documents

""" @author GroupiesM @date 2022/6/24 10:26 @introduction String formatting - The way 2 format【 recommend 】 1. brief introduction Python2.6 Start , Added a function to format strings str.format(), It enhances string formatting . The basic grammar is through {} and : To replace the old % format Function can take any number of arguments , Positions can be out of order . 2.format Formal grammar grammar :'{:${format1}}...{:${format2}}...'.format(${values}) give an example :'{:>10s}--{:<10s}'.format('hello','python') result : hello--python Reading : {:>10s} Corresponding {${format1}} {:<10s} Corresponding {${format2}} 'hello','python' Corresponding ${values} . ${values} And ${format} The combination is about 6 There are three ways of assignment , This is just one of them 3.${format} The composition of 1) ${value} When it is a character type - ( No, ${sign} and ${,}) ${fill}${align}${#}${width}${.percision}%${typecode} 2) ${value} When integer type - ( No, ${.percision}) ${fill}${align}${sign}${#}${width}${,}%${typecode} 3) ${value} When floating point ${fill}${align}${sign}${#}${width}${,}${.percision}%${typecode} ${fill} 【 Optional 】, A character filled with space ${align} 【 Optional 】, Alignment mode 、 The sign , The values to choose from are :【<、>、=、^】 < : Align left > : Right alignment ( Default ) = : Content right aligned , Place the symbol to the left of the fill character , And only for numeric types . ^ : Content centered ${sign} 【 Optional 】, There are unsigned numbers , The values to choose from are 【+、-、 Space 】 + : Plus plus +, Minus plus - - : The positive sign doesn't change , Minus plus - Space : Plus space , Sign plus - ${#} 【 Optional 】 For binary (bin)、 octal (oct)、 Hexadecimal (hex), If you add #, Will be displayed 0b/0o/0x, Otherwise it doesn't show ${width} 【 Optional 】, Total length ( Fill in the space with insufficient digits ) ${,} 【 Optional 】 Add a separator to the number , Such as :1,000,000 ${precision} 【 Optional 】, Effective digits ${typecode} 【 Optional 】, data type 、 Format 1) Pass in " String type " Parameters of s, Get the incoming object str() Return value of method ( character string - For human reading ), And format it to the specified location r, Gets the value of the incoming object repr() Return value of method ( character string - For the interpreter ), And format it to the specified location blank , Type not specified , By default s 2) Pass in " Integer types " Parameters of c, Gets the value of the incoming object chr() Return value of method (unicode Corresponding value ),10 The base range is 0 <= i <=1114111 --% Format symbol : No, b(2 Hexadecimal Numbers ) Method ,format Formatting can support -- b, Gets the value of the incoming object byte() Return value of method (2 Hexadecimal Numbers ), And format it to the specified location d,10 Hexadecimal integer o, Gets the value of the incoming object oct() Return value of method (8 Hexadecimal Numbers ), And format it to the specified location x, Gets the value of the incoming object hex() Return value of method (16 Hexadecimal Numbers ), And format it to the specified location ( English lowercase ) X, Gets the value of the incoming object hex() Return value of method (16 Hexadecimal Numbers ), And format it to the specified location ( In capital ) 3) Pass in " Floating point or decimal type " Parameters of e, The integer 、 Convert floating-point numbers to scientific counting , And format it to the specified location ( A lowercase letter e) E, The integer 、 Convert floating-point numbers to scientific counting , And format it to the specified location ( Capitalization E) f, The integer 、 Convert floating-point numbers to floating-point numbers , And format it to the specified location ( The decimal point is reserved by default 6 position ) F, ditto g, Auto adjust will be integer 、 Convert to floating point Floating point or scientific notation ( exceed 6 The number of digits is counted scientifically ), And format it to the specified location ( If it's a scientific count, it's e;) G, Auto adjust will be integer 、 Convert to floating point Floating point or scientific notation ( exceed 6 The number of digits is counted scientifically ), And format it to the specified location ( If it's a scientific count, it's E;) n, Same as 'g' %, percentage , Multiply the number by 100, Add a percent sign , Default hold 6 Decimal place ${content} 【 Mandatory 】, Content to format """
'''format format Complete syntax example 1: 16.9 1) ${fill} = ' ' A character filled with space 2) ${align} = '>' Right alignment ( Default ) 3) ${sign} = '+' Plus plus +, Minus plus - 4) ${width} = '10' Total length ( Insufficient digits make up ${fill}) 5) ${.precision} = '5', Effective digits 6) ${typecode} = 'f', data type float '''
print('{: >+010.5f}'.format(16.9)) # +16.90000
'''format format Complete syntax example 2: 10000 1) ${fill} = ' ' A character filled with space 2) ${align} = '>' Right alignment ( Default ) 3) ${sign} = '+' Plus plus +, Minus plus - 4) ${#} For binary (bin)、 octal (oct)、 Hexadecimal (hex), If you add #, Will be displayed 0b/0o/0x, Otherwise it doesn't show 5) ${width} = '10' Total length ( Insufficient digits make up ${fill}) 6) ${.precision} = '5', Effective digits 7) ${typecode} = 'o', data type octonary( Binary system ) '''
print('{: >+#10o}'.format(10000)) # +0o23420
'''format format Complete syntax example 3: 1850000 1) ${fill} = ' ' A character filled with space 2) ${align} = '>' Right alignment ( Default ) 3) ${sign} = '+' Plus plus +, Minus plus - 4) ${#} For binary (bin)、 octal (oct)、 Hexadecimal (hex), If you add #, Will be displayed 0b/0o/0x, Otherwise it doesn't show 5) ${width} = '14' Total length ( Insufficient digits make up ${fill}) 6) ${,} = ',' Add a separator to the number , Such as :1,000,000 7) ${.precision} = '2', Effective digits 8) ${typecode} = 'f', data type float '''
print('{: >+#14.2f}'.format(18500.05432)) # +18500.05
print('{: >+#14,.2f}'.format(18500.05432)) # +18,500.05
''' test result : You can see the total length 14, Number separator ${,} Also included in the total length +1850000 +1,850,000 '''
format Format
""" @author GroupiesM @date 2022/6/24 17:40 @introduction 1) ${value} When it is a character type - ( No, ${sign} and ${,}) ${fill}${align}${#}${width}${.percision}%${typecode} 2) ${value} When integer type - ( No, ${.percision}) ${fill}${align}${sign}${#}${width}${,}%${typecode} 3) ${value} When floating point ${fill}${align}${sign}${#}${width}${,}${.percision}%${typecode} """
''' format Format ${format}:【 Optional 】 P.S 1. In the following cases ${format} Add location is different 2. Use Alignment mode ${fill} Make a test comparison '''
site_dict, my_list = {
"name": " Novice tutorial ", "url": "www.runoob.com"}, [' Novice tutorial ', 'www.runoob.com']
name, age, height = ' Zhang San ', 20, 180.4
'''1.1 Does not set the specified location , By default 1.1a My name is zhang SAN , My name is zhang SAN , This year, 20 year , height 180.4 1.1b My name is *** Zhang San , My name is *** Zhang San , This year, ***20 year , height 180.4 '''
print('1.1a', ' My name is {}, My name is {}, This year, {} year , height {}'.format(name, name, age, height))
print('1.1b', ' My name is {:*>5}, My name is {:*>5}, This year, {:*>5} year , height {:*>5}'.format(name, name, age, height)) # be at the right , length 5, fill *
'''1.2 Set the specified location {0}、{1} 1.2a My name is zhang SAN , My name is zhang SAN , This year, 20 year , height 180.4 1.2b My name is @ Zhang San @@, My name is @ Zhang San @@, This year, @[email protected]@ year , height 180.4 '''
print('1.2a', ' My name is {0}, My name is {0}, This year, {1} year , height {2}'.format(name, age, height))
print('1.2b', ' My name is {0:@^5}, My name is {0:@^5}, This year, {1:@^5} year , height {2:@^5}'.format(name, age, height)) # In the middle , length 5, fill @
'''1.3 Set parameters {name}、{url} 1.3a The websites : Novice tutorial , Address www.runoob.com, profits -123 1.3b The websites : Novice tutorial , Address www.runoob.com, profits -$$123 1.3c The websites : Novice tutorial , Address www.runoob.com, profits $$-123 '''
print('1.3a', ' The websites :{name}, Address {url}, profits {profit}'.format(name=" Novice tutorial ", url="www.runoob.com", profit=-123))
print('1.3b',' The websites :{name}, Address {url}, profits {profit:$=6}'.format(name=" Novice tutorial ", url="www.runoob.com", profit=-123)) # = Right alignment , Applicable only to numbers 
print('1.3c',' The websites :{name}, Address {url}, profits {profit:$>6}'.format(name=" Novice tutorial ", url="www.runoob.com", profit=-123)) # > Right alignment 2, length 6, fill $
'''2.1 Through the dictionary dict Set parameters 2.1a The websites : Novice tutorial , Address www.runoob.com 2.1b The websites : Novice tutorial , Address www.runoob.com '''
print('2.1a', " The websites :{name}, Address {url}".format(**site_dict))
print('2.1b', " The websites :{name:<5}, Address {url:<5}".format(**site_dict)) # be at the left side , length 5, Fill in the blanks 
'''2.2 Through the list list Index setting parameters 2.2a The websites : Novice tutorial , Address www.runoob.com 2.2b The websites : Novice tutorial 🫤, Address www.runoob.com '''
print('2.2a', " The websites :{}, Address {}".format(*my_list))
print('2.2b', " The websites :{:🫤<5s}, Address {:🫤<5s}".format(*my_list)) # be at the left side , length 5, fill 🫤
'''2.3 Through the list list Index setting parameters 2.3a The websites : Novice tutorial , Address www.runoob.com 2.3b The websites : Novice tutorial , Address www.runoob.com '''
print('2.3a', " The websites :{0[0]}, Address {0[1]}".format(my_list))
print('2.3b', " The websites :{0[0]:<5s}, Address {0[1]:<5s}".format(my_list)) # be at the left side , length 5, fill 

3.1 【fill】 Fill character

""" @author GroupiesM @date 2022/6/24 16:56 @introduction 1) ${value} When it is a character type - ( No, ${sign} and ${,}) ${fill}${align}${#}${width}${.percision}%${typecode} 2) ${value} When integer type - ( No, ${.percision}) ${fill}${align}${sign}${#}${width}${,}%${typecode} 3) ${value} When floating point ${fill}${align}${sign}${#}${width}${,}${.percision}%${typecode} """
name, age, money, height, = ' Zhang San ', 20, -20, 180.4
''' Fill character ${fill}:【 Optional 】 P.S 1.${fill} The premise is ${align}, Otherwise, the report will be wrong 2.${align} The premise is ${width} , No error will be reported if it is not specified , But alignment will not work 3.${fill} Only one digit can be specified 4.${fill} When not specified , Default is space 5. The length of the content <${width} when , Trigger the filling action ; Otherwise, do nothing '''
print('1', ' My name is {}, My name is {}, This year, {} year , height {}'.format(name, name, age, height, ))
print('2', ' My name is {:>5}, My name is {:>5}, This year, {:>5} year , height {:>5}'.format(name, name, age, height, )) # be at the right , length 5, Do not specify fill 
print('3', ' My name is {:*>5}, My name is {:*>5}, This year, {:*>5} year , height {:*>5}'.format(name, name, age, height, )) # be at the right , length 5, fill *
print('4', ' My name is {:*>5}, My name is {:>5}, This year, {:>5} year , height {:>5}'.format(name, name, age, height, )) # be at the right , length 5, fill 
''' test result 1 My name is zhang SAN , My name is zhang SAN , This year, 20 year , height 180.4 2 My name is Zhang San , My name is Zhang San , This year, 20 year , height 180.4 3 My name is *** Zhang San , My name is *** Zhang San , This year, ***20 year , height 180.4 4 My name is *** Zhang San , My name is zhang SAN , This year, 20 year , height 180.4 '''

3.2 【align】 Alignment mode

""" @author GroupiesM @date 2022/6/24 16:57 @introduction 1) ${value} When it is a character type - ( No, ${sign} and ${,}) ${fill}${align}${#}${width}${.percision}%${typecode} 2) ${value} When integer type - ( No, ${.percision}) ${fill}${align}${sign}${#}${width}${,}%${typecode} 3) ${value} When floating point ${fill}${align}${sign}${#}${width}${,}${.percision}%${typecode} """
name, age, money, height, = ' Zhang San ', 20, -20, 180.4
''' Alignment mode ${align}:【 Optional 】 < : Align left > : Right alignment ( Default ) = : Content right aligned , Place the symbol to the left of the fill character , And only for numeric types . ^ : Content centered P.S 1. Different syntax formats are added at different positions , The following tests will be conducted in sequence 2.${align} The premise is ${width} , No error will be reported if it is not specified , But alignment will not work 3.${align} Align right in (=), Valid only for numeric types , If the parameter type is wrong, an error will be reported '''
''' Character string 1 My name is Zhang San 2 My name is zhang SAN 4 My name is Zhang San '''
print('1', ' My name is {:>5}'.format(name))
print('2', ' My name is {:<5}'.format(name))
# print('3', ' My name is {:=5}'.format(name)) # = Valid only for numeric classes 
print('4', ' My name is {:^5}'.format(name))
''' Digital int 1 balance -20 2 balance -20 3 balance - 20 4 balance -20 '''
print('1', ' balance {:>5}'.format(money))
print('2', ' balance {:<5}'.format(money))
print('3', ' balance {:=5}'.format(money)) # = Valid only for numeric classes 
print('4', ' balance {:^5}'.format(money))

3.3 【sign】 Number sign

""" @author GroupiesM @date 2022/6/24 16:57 @introduction 1) ${value} When it is a character type - ( No, ${sign} and ${,}) ${fill}${align}${#}${width}${.percision}%${typecode} 2) ${value} When integer type - ( No, ${.percision}) ${fill}${align}${sign}${#}${width}${,}%${typecode} 3) ${value} When floating point ${fill}${align}${sign}${#}${width}${,}${.percision}%${typecode} """
name, age, money, height = ' Zhang San ', 20, -20, 180.4
''' Number sign ${sign}:【 Optional 】 + : Plus plus +, Minus plus - - : The positive sign doesn't change , Minus plus - Space : Plus space , Sign plus - P.S 1. Different syntax formats are added at different positions , The following tests will be conducted in sequence 2.${align} The premise is ${width} , No error will be reported if it is not specified , But alignment will not work 3.${sign} Valid only for numeric types , If the parameter type is wrong, an error will be reported '''
print('1', ' Age {:}, balance {:}'.format(age, money))
print('2', ' Age {:+}, balance {:+}'.format(age, money))
print('3', ' Age {:-}, balance {:-}'.format(age, money))
print('4', ' Age {: }, balance {: }'.format(age, money))
print('5', ' Age {:$>+10}, balance {:$>+10}'.format(age, money))
''' test result 1 Age 20, balance -20 2 Age +20, balance -20 3 Age 20, balance -20 4 Age 20, balance -20 5 Age $$$$$$$+20, balance $$$$$$$-20 '''

3.4 【width】 Total length

""" @author GroupiesM @date 2022/6/24 16:58 @introduction 1) ${value} When it is a character type - ( No, ${sign} and ${,}) ${fill}${align}${#}${width}${.percision}%${typecode} 2) ${value} When integer type - ( No, ${.percision}) ${fill}${align}${sign}${#}${width}${,}%${typecode} 3) ${value} When floating point ${fill}${align}${sign}${#}${width}${,}${.percision}%${typecode} """
name, age, money, height = ' Zhang San ', 20, -2.4, 180.4
''' Total length ${width}:【 Optional 】 %s Do not specify length %1s ${width} < Character length , Don't take effect %2s ${width} = Character length , Don't take effect %10 ${width} > Character length , take effect P.S 1. Don't specify ${align} The default is ">", Right alignment 2. Don't specify ${fill} The default is " Space " 3. Of negative numbers "-" Also included in the total length , The length is 1 4. Floating point type dot "." Also included in the total length , The length is 1 '''
print('1', '{}'.format(money))
print('2', '{:1}'.format(money))
print('3', '{:2}'.format(money))
print('4', '{:3}'.format(money))
print('5', '{:4}'.format(money))
print('6', '{:5}'.format(money)) # "-2.4" The character length is 4, Appoint ${width}>=5 The filling operation will be triggered 
''' test result 1 -2.4 2 -2.4 3 -2.4 4 -2.4 5 -2.4 6 -2.4 '''

3.5 【,】 Number separator

""" @author GroupiesM @date 2022/6/24 16:58 @introduction 1) ${value} When it is a character type - ( No, ${sign} and ${,}) ${fill}${align}${#}${width}${.percision}%${typecode} 2) ${value} When integer type - ( No, ${.percision}) ${fill}${align}${sign}${#}${width}${,}%${typecode} 3) ${value} When floating point ${fill}${align}${sign}${#}${width}${,}${.percision}%${typecode} """
name, age, money, height = ' Zhang San ', 20, 100000, 11240980.456789657
''' Number separator ${,}:【 Optional 】 Add a separator to the number , Such as :1,000,000 P.S 1. typecode Integers 、 Floating point type can be added 2. Every... Before the decimal point 3 A digit number is automatically added , '''
print('1', '{:,}'.format(money))
print('3', '{:,}'.format(height))
print('3', '{:,.11}'.format(height))
''' test result 1 100,000 3 11,240,980.456789657 3 11,240,980.457 '''

3.6 【percision】 Effective digits

""" @author GroupiesM @date 2022/6/24 16:59 @introduction 1) ${value} When it is a character type - ( No, ${sign} and ${,}) ${fill}${align}${#}${width}${.percision}%${typecode} 2) ${value} When integer type - ( No, ${.percision}) ${fill}${align}${sign}${#}${width}${,}%${typecode} 3) ${value} When floating point ${fill}${align}${sign}${#}${width}${,}${.percision}%${typecode} """
''' Effective digits ${.precision}:【 Optional 】 1. character string :' Zhang San ',${.precision} Will intercept the string %s Don't specify ${precision} %.1s ${.precision} < Character length , Cut from left to right 1 position ' Zhang ' %.2s ${.precision} = Character length , Don't take effect %.10 ${.precision} > Character length , Don't take effect 2. Integers :'23',${.precision},-str.format() Specifying... To an integer is not supported ${percision}.(%-formatting Integers can be assigned ${percision}) 3. floating-point '180.45',${precision} Indicates the number of significant digits ( Floating point type means : Number of decimal places ), Default ${precision}=6 %f Don't specify ${precision}, Retain 6 Decimal place '180.450000' %.1f ${.precision} < Character length , Retain 1 Decimal place '180.4' %.2f ${.precision} = Character length , Retain 2 Decimal place '180.45' %.15f ${.precision} > Character length , Retain 15 Decimal place '180.449999999999989' '''
print('----s character string ----')
name = ' Zhang San '
print(1, '{:}'.format(name))
print(2, '{:.1}'.format(name))
print(3, '{:.2}'.format(name))
print(4, '{:.10}'.format(name))
''' 1 Zhang San 2 Zhang 3 Zhang San 4 Zhang San '''
print('----s character string ( Specify the length )----')
name = ' Zhang San '
print(1, '{:10}'.format(name))
print(2, '{:10.1}'.format(name))
print(3, '{:10.2}'.format(name))
print(4, '{:10.10}'.format(name))
''' 1 Zhang San 2 Zhang 3 Zhang San 4 Zhang San '''
print('----f floating-point ----') # Floating point type is calculated according to the number of digits after the decimal point 
height = 180.4
print(1, '{:f}'.format(height)) # # Floating point type does not specify The decimal point is reserved by default 6 position 
print(2, '{:.1f}'.format(height))
print(3, '{:.2f}'.format(height))
print(4, '{:.10f}'.format(height))
''' 1 180.400000 2 180.4 3 180.40 4 180.4000000000 '''
print('----f floating-point ( Specify the length )----')
print(1, '{:10f}'.format(height)) # Floating point type does not specify The decimal point is reserved by default 6 position 
print(2, '{:10.1f}'.format(height))
print(3, '{:10.2f}'.format(height))
print(4, '{:10.10f}'.format(height))
''' 1 180.400000 2 180.4 3 180.40 4 180.4000000000 '''

3.7 【#】2,8,16 Hexadecimal symbol

""" @author GroupiesM @date 2022/6/24 16:58 @introduction 1) ${value} When it is a character type - ( No, ${sign} and ${,}) ${fill}${align}${#}${width}${.percision}%${typecode} 2) ${value} When integer type - ( No, ${.percision}) ${fill}${align}${sign}${#}${width}${,}%${typecode} 3) ${value} When floating point ${fill}${align}${sign}${#}${width}${,}${.percision}%${typecode} """
name, age, money, height = ' Zhang San ', 20, -20, 180.4
''' 2,8,16 Hexadecimal symbol ${#}:【 Optional 】 P.S 1. Only on ${typecode} in [b,o,x,X] Effective when , But no error will be reported in other cases '''
'''2 Base number '''
print('{:b}'.format(age)) # 10100
print('{:#b}'.format(age)) # 0b10100
'''8 Base number '''
print('{:o}'.format(age)) # 24
print('{:#o}'.format(age)) # 0o24
'''16 Base number '''
print('{:x}'.format(age)) # 14
print('{:#x}'.format(age)) # 0x14

3.8 【typecode】 data type

""" @author GroupiesM @date 2022/6/24 16:59 @introduction 1) ${value} When it is a character type - ( No, ${sign} and ${,}) ${fill}${align}${#}${width}${.percision}%${typecode} 2) ${value} When integer type - ( No, ${.percision}) ${fill}${align}${sign}${#}${width}${,}%${typecode} 3) ${value} When floating point ${fill}${align}${sign}${#}${width}${,}${.percision}%${typecode} ${typecode} 【 Mandatory 】, data type 、 Format 1) Pass in " String type " Parameters of s, Get the incoming object str() Return value of method ( character string - For human reading ), And format it to the specified location r, Gets the value of the incoming object repr() Return value of method ( character string - For the interpreter ), And format it to the specified location blank , Type not specified , By default s 2) Pass in " Integer types " Parameters of c, Gets the value of the incoming object chr() Return value of method (unicode Corresponding value ),10 The base range is 0 <= i <=1114111 --% Format symbol : No, b(2 Hexadecimal Numbers ) Method ,format Formatting can support -- b, Gets the value of the incoming object byte() Return value of method (2 Hexadecimal Numbers ), And format it to the specified location d,10 Hexadecimal integer o, Gets the value of the incoming object oct() Return value of method (8 Hexadecimal Numbers ), And format it to the specified location x, Gets the value of the incoming object hex() Return value of method (16 Hexadecimal Numbers ), And format it to the specified location ( English lowercase ) X, Gets the value of the incoming object hex() Return value of method (16 Hexadecimal Numbers ), And format it to the specified location ( In capital ) 3) Pass in " Floating point or decimal type " Parameters of e, The integer 、 Convert floating-point numbers to scientific counting , And format it to the specified location ( A lowercase letter e) E, The integer 、 Convert floating-point numbers to scientific counting , And format it to the specified location ( Capitalization E) f, The integer 、 Convert floating-point numbers to floating-point numbers , And format it to the specified location ( The decimal point is reserved by default 6 position ) F, ditto g, Auto adjust will be integer 、 Convert to floating point Floating point or scientific notation ( exceed 6 The number of digits is counted scientifically ), And format it to the specified location ( If it's a scientific count, it's e;) G, Auto adjust will be integer 、 Convert to floating point Floating point or scientific notation ( exceed 6 The number of digits is counted scientifically ), And format it to the specified location ( If it's a scientific count, it's E;) n, Same as 'g' %, percentage , Multiply the number by 100, Add a percent sign , Default hold 6 Decimal place """
name, age, money, height = ' Zhang San ', ord('🫡'), -20, 180.4
''' data type ${typecode}:【 Optional 】( Not all parameters tested ) blank , Default is s, String type c, Gets the value of the incoming object chr() Return value of method (unicode Corresponding value ),10 The base range is 0 <= i <=1114111 o, Gets the value of the incoming object oct() Return value of method (8 Hexadecimal Numbers ), And format it to the specified location x, Gets the value of the incoming object hex() Return value of method (16 Hexadecimal Numbers ), And format it to the specified location '''
''' Parameters are not filled in -> The default character is s、 Integer defaults to d、 Floating point defaults to g'''
print(' _1', age) # 129761
print(' _2','{:}'.format(age)) # 129761
''' Parameters b -> 2 Base number '''
print('b_1', bin(age)) # 0b11111101011100001
print('b_2','{:b}'.format(age)) # 11111101011100001
''' Parameters o -> 8 Base number '''
print('o_1', oct(age)) # 0o375341
print('o_2','{:o}'.format(age)) # 375341
''' Parameters x -> 16 Base number '''
print('x_1', hex(age)) # 0x1fae1
print('x_2','{:x}'.format(age)) # 1fae1

3.9 %-formatting contrast str.format()

""" @author GroupiesM @date 2022/6/27 11:06 @introduction In most cases ,% Format match format Formatting can achieve the same function , In the following case, two formats are used to output the same format results But there are also some differences : The differences between the tests are summarized as follows : 1) ${typecode}='b': For binary %: I won't support it format: Support 2) ${typecode}='': Leave blank %: I won't support it format: Support , Default is s( character string ) 3) ${.percision}: %: Integer when adding ${.percision}, Indicates the number of significant digits format: Integer cannot be added 4) ${fill}: Manually specify the separator %: I won't support it format: Support 5) ${,}: Add a separator to the number , Such as :1,000,000 %: I won't support it format: Support """
'''% Format symbol Complete syntax example 1: 16.9 1) ${flag} = '+' Right alignment : The plus sign of a positive number , Plus minus sign of negative number 2) ${width} = '10' Total length ( Fill in the space with insufficient digits ) 3) ${precision} = '5', Effective digits 4) ${typecode} = 'f', data type float '''
print('%(money)+10.5f' % {
'money': 16.9}) # +16.90000
'''format format Complete syntax example 1: 16.9 1) ${fill} = ' ' A character filled with space 2) ${align} = '>' Right alignment ( Default ) 3) ${sign} = '+' Plus plus +, Minus plus - 4) ${width} = '10' Total length ( Insufficient digits make up ${fill}) 5) ${precision} = '5', Effective digits 6) ${typecode} = 'f', data type float '''
print('{: >+010.5f}'.format(16.9)) # +16.90000
'''% Format symbol Complete syntax example 2: 10000 1) ${flag} = + Right alignment : The plus sign of a positive number , Plus minus sign of negative number 2) ${#} For binary (bin)、 octal (oct)、 Hexadecimal (hex), If you add #, Will be displayed 0b/0o/0x, Otherwise it doesn't show 3) ${width} = 10 Total length ( Fill in the space with insufficient digits ) 4) ${precision} = 5, Effective digits 5) ${typecode} = f, data type float '''
print('%(money)#+10o' % {
'money': 10000}) # +0o23420
'''format format Complete syntax example 2: 10000 1) ${fill} = ' ' A character filled with space 2) ${align} = '>' Right alignment ( Default ) 3) ${sign} = '+' Plus plus +, Minus plus - 4) ${#} For binary (bin)、 octal (oct)、 Hexadecimal (hex), If you add #, Will be displayed 0b/0o/0x, Otherwise it doesn't show 5) ${width} = '10' Total length ( Insufficient digits make up ${fill}) 6) ${precision} = '5', Effective digits 7) ${typecode} = 'f', data type float '''
print('{: >+#10o}'.format(10000)) # +0o23420

Four 、f-String

Grammar details reference :PEP 3101 – Advanced string formatting

Tired , I don't want to test it


22/06/28

M


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved