Legacy formatting:%s,%d
1. Fill in the formatted content sequentially
s = "Hello%s, hello%d"% ("World", "page") print (s)
Result: ' Hello World, hello 100 '
2. Use keyword parameters
s= "% (name) s age% (age) d"%{"name": "Tom", "Age": 10}
Print (s)
Result: Tom name 10
Commonly used formatting symbols
%s corresponds to string type (str)
%d (int) corresponding to the decimal integer type
%f corresponding floating-point number (float)
%r corresponding string (repr)
Using the format () function
1. No parameter condition
s = "Hello {}, hello {}". Format ("World", "Python") print (s)
Result: "Hello World, Hello Python"
2. Position parameters
s = "Hello {1}, hello {0}". Format ("World", "Python") print (s)
Result: "Hello Python, Hello World"
3. Key parameters
s = "Hello {first}, Hello{second}". Format (first= "World", second= "Python") print (s)
Result: "Hello World, Hello Python"
4, position parameters and keyword parameters mixed
Position parameter is placed in front of the keyword parameter, otherwise error
s = "Hello {first}, hello{0}". Format (Python, first= "World") print (s)
Result: "Hello World, Hello Python"
5, "!a" (using ASCII ()), "!s" (using str ()), "!r" (using Repr ()) can be converted before formatting the corresponding values.
in [+]: Contents = "eels" in []: Print ("My hovercraft was full if {}.".) Format (contents)) My hovercraft is full if eels. In [All]: print ("My hovercraft is full if {!r}."). Format (contents)) My hovercraft is full if ' eels '. in [+]: print ("My hovercraft is full if {!s}.". Format (contents)) My hovercraft is full if eels. in [+]: print ("My hovercraft is full if {!a}.". Format (contents)) My hovercraft is full if ' eels '.
6, after the field can be used ":" and format instructions, better control format.
(1), the next code to approximate π to 3 digits after the decimal point
Import Mathprint ("The value of PI is approximately {0:.3f}.") Format (MATH.PI))
Results: 3.142
(2), ":" followed by an integer to limit the minimum width of the field
Table = {' Sjoerd ': 4127, ' Jack ': 4098, ' dcab ': 7678}for name, phone in Table.items (): print (' {0:10} ==> {1:10d} '. fo Rmat (name, phone))
Results:
Jack ==> 4098Dcab ==> 7678Sjoerd ==> 4127
Summarize:
% formatted as Python built-in operator, commonly used for this article mentioned in these, there are some other, such as binary related, want to know can find other information. Format uses Python's built-in functions, and there are many more uses for format, such as formatting, precision determination, padding and alignment, and so on.
Python string format output%d,%s and Format function