1. 通过位置来填充字符串
>>> '{0}, {1}, {2}'.format('a', 'b', 'c')
'a, b, c'
>>> '{2}, {1}, {0}'.format('a', 'b', 'c')
'c, b, a'
>>> '{0}{1}{0}'.format('a', 'b')
'aba'
2. 通过key来填充字符串
>>> print 'hello {name1} i am {name2}'.format(name1='Kevin',name2='Tom')
hello Kevin i am Tom
3. 通过下标来填充字符串
>>> names=['Kevin','Tom']
>>> print 'hello {names[0]} i am {names[1]}'.format(names=names)
>>> print 'hello {0[0]} i am {0[1]}'.format(names)
hello Kevin i am Tom
4. 通过属性匹配来填充字符串
>>> class Point:
... def __init__(self, x, y):
... self.x, self.y = x, y
... def __str__(self):
... return 'Point({self.x}, {self.y})'.format(self=self)
...
>>> str(Point(4, 2))
'Point(4, 2)'
>>> names={'name':'Kevin','name2':'Tom'}
>>> print 'hello {names[name]} i am {names[name2]}'.format(names=names)
hello Kevin i am Tom
>>> '{:,}'.format(1234567890)
'1,234,567,890'
>>> points = 19
>>> total = 22
>>> 'Correct answers: {:.2%}'.format(points/total)
'Correct answers: 86.36%'
>>>'{:.2f}'.format(3.1415926)
3.14
>>> '{:.0f}'.format(3.1415926)
3