Reprinted from: http://www.cnblogs.com/kaituorensheng/p/5709970.html
Python since 2.6, a new format string function Str.format (), powerful, can replace the original%
Note : The following operating version is python2.7
mapping example
Grammar
by {} and: replace%
By location
>>> ' {0} was {1} '. Format (' Jihite ', ' 4 years old ') ' Jihite are 4 years old ' >>> ' {0} is {1} {0} '. Format (' Jihi Te ', ' 4 years old ') ' Jihite are 4 years old Jihite '
The Format function allows you to accept unlimited number of arguments, unlimited order
by keyword
>>> ' {name}:{age} '. Format (age=4,name= ' jihite ') ' jihite:4 ' >>> ' {name}:{age} '. Format (age=4,name= ' Jihite ', locate= ' Beijing ') ' Jihite:4 '
Use = To assign a value to a variable in format parentheses
Through object properties
>>> class Person: ... def __init__ (self, Name, age): ... Self.name,self.age = name, age ... def __func__ (self): ... Return "This guy is {self.name}, was {self.age} old". Format (self=self) ... >>> s =person (' Jihite ', 4) >>> s . __func__ () ' This guy is Jihite, was 4 old '
by subscript
>>> ' {0[0]} is {0[1]} years old! '. Format ([' Jihite ', 4]) ' Jihite is 4 years old! ' >>> ' {0} is {1} years old! '. Format (' Jihite ', 4) ' Jihite is 4 years old! '
is actually through the location
Format qualifier
Through {}: symbol
Fill and align
^<> are centered, left-aligned, right-aligned, followed by width
>>> ' {: >10} '. Format (' jihite ') ' jihite ' >>> ' {: <10} '. Format (' jihite ') ' Jihite ' > >> ' {: ^10} '. Format (' jihite ') ' jihite '
Accuracy and type F
Accuracy is often used in conjunction with F
>>> ' {:. 2f} '. Format (3.1415) ' 3.14 ' >>> ' {:. 4f} '. Format (3.1) ' 3.1000 '
In-process conversion
>>> ' {: b} '. Format (Ten) ' 1010 ' >>> ' {: o} '. Format (Ten) ' >>> ' {:d} '. Format (Ten) ' >> > ' {: x} '. Format (Ten) ' A '
where b o D x indicates two or eight, 16 or 16 binary respectively
Thousands separator
>>> ' {:,} '. Format (1000000) ' 1,000,000 '
>>> ' {:,} '. Format (100000.23433)
' 100,000.23433 '
>>> ' {:,} '. Format (' Abcedef ') Traceback (most recent call last): File "<stdin>", line 1, in <module& Gt Valueerror:cannot specify ', ' with ' s '.
In particular, the accuracy and type of use is very convenient.
Use of the Python format function