自python2.6开始,新增了一种格式化字符串的函数str.format(),可谓威力十足。 它通过{}和:来代替%

format方法被用于字符串的格式化输出。


In [1]:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
print('{0}+{1}={2}'.format(5, 6, 5 + 6))


5+6=11

可见字符串中大括号内的数字分别对应着format的几个参数。

若省略数字:


In [5]:
print('{}+{}={}'.format(5, 6, 5 + 6))


5+6=11

可以得到同样的输出结果。但是替换顺序默认按照[0],[1],[2]...进行。

若替换{0}和{1}:


In [6]:
print('{1}+{0}={2}'.format(5, 6, 5 + 6))


6+5=11

输出字符串:


In [7]:
print('{0} am {1}'.format('I', 'John'))


I am John

输出参数的值:


In [9]:
length = 4
name = 'John'
print('the length of {0} is {1}'.format(name, length))


the length of John is 4

精度控制:(输出小数点后5位)


In [12]:
print('{0:.5}'.format(1 / 3))


0.33333

宽度控制:(小数点.也占1位)


In [13]:
print('{0:7}{1:7}'.format('use', 'python'))


use    python 

精宽度控制(宽度内居左):


In [15]:
print('{0:<7.3}!!'.format(1 / 7))


0.143  !!

宽度内居右:


In [17]:
print('**{0:>7.3}'.format(1 / 7))


**  0.143

宽度内居中:


In [20]:
print('*{0:^7.3}*'.format(1 / 7))


* 0.143 *

数字精度与类型f, 精度常跟类型f一起使用。


In [23]:
print('{:.3f}'.format(2017.123456789))


2017.123

其中.3表示长度为3的精度,f表示float类型。

其他类型:

b、d、o、x分别是二进制、十进制、八进制、十六进制。


In [28]:
print('2017的二进制:{:b}'.format(2017))
print('2017的十进制:{:d}'.format(2017))
print('2017的八进制:{:o}'.format(2017))
print('2017的十六进制:{:x}'.format(2017))


2017的二进制:11111100001
2017的十进制:2017
2017的八进制:3741
2017的十六进制:7e1

用,号还能用来做金额的千位分隔符。


In [29]:
print('{:,}'.format(20170608))


20,170,608

关键字参数

字符串的format函数可以接受数量不限的参数,参数位置可以不按顺序,参数可以不使用或者使用多次,非常灵活


In [21]:
print('{domain}, {year}'.format(domain='www.python.org', year='2017'))


www.python.org, 2017

In [2]:
print('{domain}, {year}'.format(year='2017', domain='www.python.org'))


www.python.org, 2017