Starting with python2.6, a new function of formatting strings Str.format () is powerful. So, what's the advantage of him comparing to the format of the previous%-formatted string? Let us uncover its shy veil.
Grammar
It replaces% by {} and:.
The mapping sample
Through position
In [1]: ' {0},{1} '. Format (' Kzc ', a)
out[1]: ' kzc,18 ' in
[2]: ' {},{} '. Format (' Kzc ', @)
out[2]: ' kzc,18 ' In
[3]: ' {1},{0},{1} '. Format (' Kzc ',%)
OUT[3]: ' 18,kzc,18 '
The Format function of the string can accept an unlimited number of parameters, the position can be not in order, can not be used or several times, but 2.6 can not be empty {},2.7 can be.
by keyword parameter
In [5]: ' {name},{age} '. Format (age=18,name= ' Kzc ')
out[5]: ' kzc,18 '
Through object properties
Class Person:
def __init__ (self,name,age):
self.name,self.age = Name,age
def __str__ (self): return
' This was {self.name},is {self.age} old. Format (self=self)
In [2]: str (person (' kzc ',))
out[2]: ' This guy is Kzc,is '
by subscript
In [7]: p=[' kzc ', +] in
[8]: ' {0[0]},{0[1]} '. Format (p)
out[8]: ' kzc,18 '
With these convenient "mapping" way, we have a lazy weapon. The basic Python knowledge tells us that lists and tuple can be "broken" into ordinary parameters to the function, and dict can be broken into the keyword parameters to the function (through and *). So you can easily pass a list/tuple/dict to the Format function. Very flexible.
Format Qualifier
It has a rich "format qualifier" (syntax is {} with: number), such as:
Padding and alignment
padding is often used in conjunction with alignment
^, <, > are centered, left aligned, right aligned, with width behind
: The character followed by a fill, can only be one character, not specified by default is filled with space
Like what
in [n]: ' {: >8} '. Format (' 189 ')
out[15]: ' 189 ' in
[]: ' {: 0>8} '. Format (' 189 ')
out[16]: ' 00000189 ' in
[]: ' {: a>8} '. Format (' 189 ')
out[17]: ' aaaaa189 '
Precision and type F
precision is often used with type F
in [[]: ' {:. 2f} '. Format (321.33345)
out[44]: ' 321.33 '
Where. 2 represents the precision of length 2, and F represents float type.
Other types
The main is the system, B, D, O, X is binary, decimal, octal, hexadecimal.
In [si]: ' {: b} '. Format (
out[54]: ' 10001 ' in
[+]: ' {:d} '. Format (
out[55]: ' in [+
]: ' {: O } '. Format (
out[56]: ' ' in
[]: ' {: x} '. Format (
out[57]: ' 11 '
Use, the number can also be used to do the amount of thousands separator.
In [all]: ' {:,} '. Format (1234567890)
out[47]: ' 1,234,567,890 '