Python standard library: built-in Function format (value [, format_spec]), pythonformat_spec
This function formats the value in the format of format_spec. However, the function explains that format_spec is determined by the value type. Different types have different formatting interpretations. When the format_spec parameter is null, this function is equivalent to the str (value) function.
In fact, this function is called to convert format (value, format_spec) to type (value ). the _ format _ (format_spec) method is called. Therefore, the _ format _ () method is searched for in the value type. If this method is not found, an exception TypeError is returned.
The format_spec format 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" | "%"
Fill indicates that any character can be entered.
Align is the Alignment Method, <is the left alignment,> is the right alignment, and ^ is the center alignment.
Sign is a symbol, + indicates a positive number, and-indicates a negative number.
Width indicates the total number of output digits.
Precision is the number of decimal reserved digits.
Type indicates the expression of the output numeric value. For example, B Indicates binary, E indicates exponential, and X indicates hexadecimal.
Example:
#format()print(format(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 output is as follows:
2918
500
0000003.14
03.14
3.141590E + 00
Test
Test
Test
Cai junsheng QQ: 9073204 Shenzhen