Transferred from: http://blog.csdn.net/handsomekang/article/details/9183303
Since python2.6, a new function Str.format () that formats the string has been added to the power. So, what's the advantage of being compared to the previous% format string? Let us uncover the veil of its shy.
Grammar
It replaces% with {} and:.
Map sample
By location
In [1]: ' {0},{1} '. Format (' Kzc ', +) 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 parameter, and the position can beNot in order, you can not use ormultiple, but 2.6 cannot be empty {},2.7.
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 guy 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 ', 18]in [8]: ' {0[0]},{0[1]} '. Format (P) out[8]: ' kzc,18 '
With these convenient "mapping" methods, we have a lazy weapon. Basic Python knowledge tells us that list and tuple can be "broken" into normal 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:), for example:
fill and align
Fill is used in conjunction with alignment
^, <, > center, left, right, back bandwidth
: character followed by padding , can only be a single character, not specified by default is filled with spaces
such as
in [+]: ' {: >8} '. Format (' 189 ') out[15]: ' 189 ' in [+]: ' {: 0>8} '. Format (' 189 ') out[16]: ' 00000189 ' in [+]: ' {:a> 8} '. Format (' 189 ') out[17]: ' aaaaa189 '
Accuracy and type F
Accuracy is often used in conjunction with Type F
in []: ' {:. 2f} '. Format (321.33345) out[44]: ' 321.33 '
Where. 2 represents a precision of 2 length, and F represents a float type.
Other types
Mainly in the system, B, D, O, X are binary, decimal, octal, hexadecimal.
In [si]: ' {: b} '. Format (out[54]: ' 10001 ' in []: ' {:d} '. Format (+) out[55]: ' + ' in [+]: ' {: o} '. Format (+) out[56]: ' 21 ' In []: ' {: x} '. Format (out[57]: ' 11 '
Use, the number can also be used to make the amount of thousands separator.
in [+]: ' {:,} '. Format (1234567890) out[47]: ' 1,234,567,890 '
The Str.format () function in Python