This function formats values in format_spec format, whereas function interpretation format_spec is based on the type of value to determine, different types have different formatting interpretations. When the parameter format_spec is empty, this function is equivalent to the way the function str (value) is .
In fact, when this function is called, the format (value, Format_spec) is converted to type (value). __format__ (format_spec) method __format__ ()is found in the value type, andif this method is not found, an exception is returned TypeError .
where format_spec is written in the following form:
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" | "%"
Fill means that any character can be filled in.
Align is alignment,< is left- aligned, > is Right-aligned,^ is center-aligned.
sign is a symbol, + denotes a plus sign, - denotes a minus.
Width is the number of digits, indicating how many digits are output in total.
Precision is the number of decimal reserved digits.
Type is the representation of the output numeric value, for example, b is a binary representation, for example , E is an exponential representation, for example , X is a hexadecimal representation.
Example:
#format () print (2918) print (Format (0x500, ' X ')) print (Format (3.14, ' 0=10 ')) print (Format (3.14159, ' 05.3 ')) Print (Format (3.14159, ' E ')) Print (Format (' Test ', ' <20 ') print (Format (' Test ', ' >20 ')) Print (Format (' Test ', ' ^20 ‘))
The resulting output is as follows:
2918
500
0000003.14
03.14
3.141590E+00
Test
Test
Test
Cai Junsheng qq:9073204 Shenzhen
Python standard library: Built-in function format (value[, Format_spec])