Python tutorials (Learning Python line): 3 Python string format function of formatting Detailed (lower) piece

Python tutorials (Python learning course): Next to speak with you 3 of the Python string formatting format function explain (at) articles

 

Format qualifier

format through the rich "Format Qualifiers" ({} syntax is the band: number) format for content requires the completion of a more detailed formulation.

Hexadecimal conversion

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

 

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

: Back number with fill characters, only one character is not specified, the default is filled with spaces, and the filling is often used in conjunction with alignment ^, <,> 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

: Back number setting accuracy (accuracy of plus to start.), Then ends with F, 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}

More Python tutorials will continue to update everyone!

Guess you like

Origin www.cnblogs.com/cherry-tang/p/10968774.html