The format string formatting functions Python3 Detailed (lower)

Format qualifier

format through the rich "Format Qualifiers" (The syntax is {}the band :number) to complete the development of more detailed content required format.

Hexadecimal conversion

We can then develop a different character in the qualifiers for the conversion of formatted hexadecimal numbers, corresponding hexadecimal form:

character meaning
b Binary
c Unicode character
d Decimal integer
O Octal
x Hexadecimal number, a lowercase f to
X Hexadecimal number, A to F Uppercase
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))
复制代码

Sample results:

1100011
c
99
143
63
63
复制代码

Filling aligned

:Number of characters after the band filling, only one character is not specified, the default is filled with spaces, and often used in conjunction with alignment padding, ^, <, >are centered, left aligned, right aligned, the back width.

N = 99
print('{:>8}'.format(N))
print('{:->8}'.format(N))
print('{:-<8}'.format(N))
print('{:-^8}'.format(N))
复制代码

Sample results:

      99
------99
99------
---99---
复制代码

accuracy

:Behind the number setting accuracy (at .start plus precision), then f ended, if not set, the default is the precision of 6, automatic rounding positive and negative numbers can be displayed with a symbol mark.

N = 99.1234567
NN = -99.1234567
print('{:f}'.format(N))
print('{:.2f}'.format(N))
print('{:+.2f}'.format(N))
print('{:+.2f}'.format(NN))
复制代码

Sample results:

99.123457
99.12
+99.12
-99.12
复制代码

Escape

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

p = 'Python'
S = 'I like {}, and {{0}}'.format(p)
print(S)
复制代码

Sample results:

I like Python, and {0}
复制代码

Reproduced in: https: //juejin.im/post/5cf3d5ed518825745841767f

Guess you like

Origin blog.csdn.net/weixin_34072857/article/details/91436808