Both the string Str.format () and the Formatter class Use the same formatted string. The formatted character uses curly braces {} to contain the replaced field, and any characters that are not in curly braces are directly output without conversion. Therefore, in order to output curly braces, you need to use a special way to output curly braces using double curly braces, such as { { to output {,}} to output }.
The syntax for formatting a string is as follows:
Replacement_field:: = "{" [Field_name] ["!" conversion] [":" Format_spec] "}"
Field_name:: = Arg_name ("." Attribute_name | "[" Element_index "]") *
Arg_name:: = [identifier | integer]
Attribute_name:: = Identifier
Element_index:: = Integer | Index_string
Index_string:: = <any source character except "]" > +
Conversion:: = "R" | "S" | A
Format_spec:: = <described in the next section>
3.1.3.1 format string Description strings
The syntax for the format string description strings is as follows:
Format_spec:: = [[Fill]align][sign][#][0][width][,][.precision][type]
Fill:: = <any character>
Align:: = "<" | ">" | "=" | "^"
Sign:: = "+" | "-" | " "
Width:: = integer
Precision:: = integer
Type:: = "B" | "C" | "D" | "E" | "E" | "F" | "F" | "G" | "G" | "N" | "O" | "S" | "X" | "X" | "%"
examples of 3.1.3.2 formatted strings
The following example uses the new format instead of using the old % format method. In most cases, however, the new format syntax is similar to the old syntax. Use curly braces {} and semicolons: Instead of percent sign %. For example , '%03.2f ' is represented as ' {: 03.2f} '. However, there are new options and different ways to use the new format, as in the following example:
To access parameters by location:
#string
Import string
Print (' {0},{1},{2} '. Format (' A ', ' B ', ' C ')
Print (' {},{},{} '. Format (' A ', ' B ', ' C ')
Print (' {2},{1},{0} '. Format (' A ', ' B ', ' C ')
Print (' {2},{1},{0} '. Format (* ' abc '))
Print (' {2},{1},{2} '. Format (' abc ', ' 123 ', ' 888 ')
The resulting output is as follows:
A,b,c
A,b,c
C,b,a
C,b,a
888,123,888
In this example, the statement ' {0},{1},{2} '. Format (' A ', ' B ', ' C ') in 0,1,2 is the ordinal of the positional parameter, {0} means toreplace the output with the parameter 'a' in this place, the ordinal of the positional parameter is from 0 starts counting, increasing from left to right.
In the statement' {},{},{} '. Format (' A ', ' B ', ' C '), if the position parameter is not specified, it is output by the default position, and if the number of curly braces is less than the number of positional arguments, then the output is ignored by the subsequent arguments. In the statement{2},{1},{0} '. Format (' A ', ' B ', ' C '), you can see that the position parameter can be placed in a different output position, so its output becomesCThe letters are output first, the last isaoutput. In the statement' {2},{1},{0} '. Format (* ' abc '), the parameter list parsing mechanism is used here, in the parameters 'ABC' before adding an asterisk*is to change the parameter to a list before processing, the position of each item in the list corresponds to the position parameter indicated at the output, so the output of this statement isC,b,athe order. In the statement' {2},{1},{2} '. Format (' abc ', ' 123 ', ' 888 '), the main point is that the positional parameters can be repeated or some positional parameters may be missing.
To access parameters by name:
Print (' Mouse: ({x},{y}) '. Format (x = ' + ', y = ' 200 ')
Mousept = {' x ': ' $ ', ' Y ': ' 888 '}
Print (' Mouse: ({x},{y}) '. Format (**mousept))
The resulting output is as follows:
Mouse: (100,200)
Mouse: (200,888)
In the statement ' mouse: ({x},{y}) '. Format (x = ' + ', y = ' $ ') , there is no number for the previous positional parameter, but instead of the name X, y . In the format parameter, of course, it is necessary to pass in the keyword parameter, in order to match these keyword parameters with the specified name of the output. In the statement ' mouse: ({x},{y}) '. Format (**mousept) , the dictionary parameter mousept is used directly to pass in, Then use two asterisks to parse the dictionary parameter back into the keyword parameter.
Properties for Access Parameters:
Print (' property access to complex number, real part ={0.real} imaginary part ={0.imag} '. Format (3 + 4j))
Class point:
def __init__ (self, x, y):
self.x, self.y = x, y
def __str__ (self):
Return ' point ({self.x}, {self.y}) '. Format (self = self)
Print (str (point (5,5)))
The output results are as follows:
Property access of complex number, real part =3.0 imaginary part =4.0
Point (5, 5)
In the statement ' Complex property access, real part ={0.real} imaginary part ={0.imag} '. Format (3 + 4j) , The properties of the complex are accessed directly in the format, and the resulting property can be output directly in the string. In the statement ' point ({self.x}, {self.y}) '. Format (self = self) , you can directly access the properties of the class, and the result prints the value of the Class property. This is much simpler than re-writing the attributes in the Format function, with fewer characters to enter.
Access the entry for the parameter:
XY = (20, 30)
Print (' X- axis : {0[0]}, Y - axis : {0[1]} '. Format (XY))
The output results are as follows:
X- Axis : Y- axis :
In this example, you can see that the item that accesses the tuple directly in the format, such as 0[0] , represents the first item that accesses the first parameter, and0[1] represents the second item that accesses the first parameter.
Replace %s and %r with !s and !r :
Print (' repr (): {!r}; str (): {!s} '. Format (' abc ', ' 123 '))
The output results are as follows:
Repr (): ' ABC '; STR (): 123
With this example, you can see the substitution of %swith!s, which issimpler and easier, and the same !r replaces the %r.
string arrangement and width alignment
Print (' {: <30} '. Format (' left justified '))
Print (' {: >30} '. Format (' right-justified '))
Print (' {: ^30} '. Format (' Center-aligned '))
Print (' {:* ^30} '. Format (' Center-aligned ')
The output results are as follows:
Align Left
Align Right
Center Alignment
Center Align *************
Replaces %+f,%-f , and % F, as well as floating-point number formatting for the specified symbol
Print (' {: +f}; {: +f} '. Format (0.618,-0.618))
Print (' {: F}; {: F} '. Format (0.618,-0.618))
Print (' {: F}; {: F} '. Format (0.618,-0.618))
Print (' {:-F}; {:-F} '. Format (0.618,-0.618)
The output results are as follows:
+0.618000; -0.618000
0.618000; -0.618000
0.618000; -0.618000
0.618000; -0.618000
Replace %x and %o, with the same value formatted as a different input output at the same time
Print (' int: {0:d}; Hex: {0:x}; Oct: {0:o}; Bin: {0:b} '. Format (55))
Print (' int: {0:d}; Hex: {1:x}; Oct: {0:o}; Bin: {0:b} '. Format (55, 64))
Print (' int: {0: #d}; Hex: {0: #x}; Oct: {0: #o}; Bin: {0: #b} '. Format (55))
The output results are as follows:
int:55; hex:37; oct:67; bin:110111
int:55; hex:40; oct:67; bin:110111
int:55; hex:0x37; oct:0o67; bin:0b110111
Use commas as separators for thousands
Print (' {:,} '. Format (9876543210))
Print (' {0:,} '. Format (88888888888889876543210))
The output results are as follows:
9,876,543,210
88,888,888,888,889,876,543,210
Output percent value when formatting
Print (' percent output:{:. 2%} '. Format (50/100))
Print (' percent output:{:. 2%} '. Format (1.08))
The output results are as follows:
Percent output:50.00%
Percent output:108.00%
Output time format when formatting
Import datetime
D = Datetime.datetime (2015, 1, 13, 12, 30, 59)
Print (' time format: {:%y-%m-%d%h:%m:%s} '. Format (d))
The output results are as follows:
Time format: 2015-01-13 12:30:59
Nested formatting parameters
For align, the text in Zip (' <^> ', [' left ' , ' Middle ', ' right '):
Print (' {0:{fill}{align}16} '. Format (text, fill=align, align=align))
width = 5
For NUM in range (5, 12):
For base in ' Dxob ':
Print (' {0:{width}{base}} '. Format (num, base=base, width=width), end = ')
Print ()
The output results are as follows:
Left <<<<<<<<<<<<<<<
^^ ^^ ^^ ^ ^^ ^^ ^^ ^^
>>>>>>>>>>>>>>> Right
5 5 5 101
6 6 6 110
7 7 7 111
8 8 10 1000
9 9 11 1001
Ten A 12 1010
B 13 1011
Multiple formatting templates and parallel
IPADDR = [192, 168, 0, 8]
Print (' {: 02x}{:02x}{:02x}{:02x} '. Format (*IPADDR))
The output results are as follows:
c0a80008
Cai Junsheng qq:9073204 Shenzhen
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
3.1.3 Syntax for formatting strings