format()是python2.6新增的一个格式化字符串的方法,功能非常强大,有可能在未来完全替代%格式化方法,相比 % ,format()的优点有:

  • 1 .格式化时不用关心数据类型的问题,format()会自动转换,而在%方法中,%s用来格式化字符串类型,%d用来格式化整型;
  • 2. 单个参数可以多次输出,参数顺序可以不同
  • 3. 填充方式灵活,对齐方式强大

 

1. 通过位置来填充字符串

 


 
  1. >>> '{0}, {1}, {2}'.format('a', 'b', 'c')

  2. 'a, b, c'

  3. >>> '{2}, {1}, {0}'.format('a', 'b', 'c')

  4. 'c, b, a'

  5. >>> '{0}{1}{0}'.format('a', 'b')

  6. 'aba'

 

 

2. 通过key来填充字符串

 


 
  1. >>> print 'hello {name1} i am {name2}'.format(name1='Kevin',name2='Tom')

  2. hello Kevin i am Tom

 

 

3. 通过下标来填充字符串

 


 
  1. >>> names=['Kevin','Tom']

  2. >>> print 'hello {names[0]} i am {names[1]}'.format(names=names)

  3. >>> print 'hello {0[0]} i am {0[1]}'.format(names)

  4. hello Kevin i am Tom

 

 

4. 通过属性匹配来填充字符串

 


 
  1. >>> class Point:

  2. ... def __init__(self, x, y):

  3. ... self.x, self.y = x, y

  4. ... def __str__(self):

  5. ... return 'Point({self.x}, {self.y})'.format(self=self)

  6. ...

  7. >>> str(Point(4, 2))

  8. 'Point(4, 2)'

 

 

5. 通过字典的key来填充字符串


 
  1. >>> names={'name':'Kevin','name2':'Tom'}

  2. >>> print 'hello {names[name]} i am {names[name2]}'.format(names=names)

  3. hello Kevin i am Tom


6. 使用","作用千位分隔符


 
  1. >>> '{:,}'.format(1234567890)

  2. '1,234,567,890'


7. 百分数显示


 
  1. >>> points = 19

  2. >>> total = 22

  3. >>> 'Correct answers: {:.2%}'.format(points/total)

  4. 'Correct answers: 86.36%'


8. 小数位保留


 
  1. >>>'{:.2f}'.format(3.1415926)

  2. 3.14

  3. >>> '{:.0f}'.format(3.1415926)

  4. 3