python中format()方法格式化字符串

format()是python2.6新增的一个格式化字符串的方法,功能非常强大,有可能在未来完全替代%格式化方法,相比 % ,format()的优点有:
  • 1 .格式化时不用关心数据类型的问题,format()会自动转换,而在%方法中,%s用来格式化字符串类型,%d用来格式化整型;
  • 2. 单个参数可以多次输出,参数顺序可以不同
  • 3. 填充方式灵活,对齐方式强大

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)'

5. 通过字典的key来填充字符串
>>> names={'name':'Kevin','name2':'Tom'}
>>> print 'hello {names[name]}  i am {names[name2]}'.format(names=names)
hello Kevin i am Tom

6. 使用","作用千位分隔符
>>> '{:,}'.format(1234567890)
'1,234,567,890'

7. 百分数显示
>>> points = 19
>>> total = 22
>>> 'Correct answers: {:.2%}'.format(points/total)
'Correct answers: 86.36%'

8. 小数位保留
>>>'{:.2f}'.format(3.1415926)
3.14
>>> '{:.0f}'.format(3.1415926)
3