Format qualifier

Format uses rich “format qualifiers” (syntax {} with a:) to specify in greater detail what needs to be formatted.

Hexadecimal conversion

We can specify different characters in the qualifier to format the base conversion of numbers, the corresponding table of the base:

character meaning
b binary
c Unicode characters
d Decimal integer
o Octal number
x Hexadecimal number, a to F lowercase
X Hexadecimal number, capital A to F
N = 99
print('{:b}'.format(N))
print('{:c}'.format(N))
print('{:d}'.format(N))
print('{:o}'.format(N))
print('{:x}'.format(N))
print('{:X}'.format(N))
Copy the code

Example results:

1100011
c
99
143
63
63
Copy the code

Fill and align

If not specified, padding is used with a space. Padding is often used with alignment. ^, <, and > are centered, left, and right, respectively, followed by a width.

N = 99
print('8} {: >'.format(N))
print('8} {: - >'.format(N))
print('{: - < 8}'.format(N))
print('{: - ^ 8}'.format(N))
Copy the code

Example results:

99 99-99 -- -- -- -- -- - -- -- -- -- -- -- -- -- -- -- -- 99Copy the code

precision

Precision is set after: sign (to. Start with precision), and then end with f. If not set, the precision is 6 by default, automatically rounded, and the number plus or minus signs can be displayed with symbols.

N = 99.1234567
NN = 99.1234567
print('{:f}'.format(N))
print('{:.2f}'.format(N))
print('{:+.2f}'.format(N))
print('{:+.2f}'.format(NN))
Copy the code

Example results:

99.123457 99.12 + 99.12 to 99.12Copy the code

escape

We can use curly braces {} to escape curly braces.

p = 'Python'
S = 'I like {}, and {{0}}'.format(p)
print(S)
Copy the code

Example results:

I like Python, and {0}
Copy the code