python中有两种格式化输出字符串的方式:格式化表达式、format()方法。当然,还有一个简化操作的内置format()函数。
它们绝大部分功能都是重复的,熟悉printf的可以考虑使用格式化表达式,否则使用format()更友好些,因为它像处理函数参数一样,但format()有时候可能写的要更复杂。
格式化表达式
格式化表达式类似于printf的风格,在字符串中使用%
作为占位符。本文只是介绍python中的一些特性,如有需要请自行搜索printf用法。
>>> who1 = "long">>> who2 = "shuai">>> "hello %s world" % "your"'hello your world'>>> "hello %s world" % who1'hello long world'>>> "hello %s world" % (who1)'hello long world'>>> "hello %s %s world" % (who1, who2)'hello long shuai world'
字符串和替换目标之间也使用%
分隔,且替换部分可以有多个(使用括号包围),可以使用变量。
替换目标还可以使用字典,这时在字符串中的%
占位符可以以key的方式来引用:
>>> "%(name1)s with %(name2)s" % {"name1":"longshuai", "name2":"xiaofang"}'longshuai with xiaofang'
用字典的形式,可以让表达式格式化更模板化。例如:
>>> reply = """... hello %(name)s!... Your age is %(age)d""">>>>>> values = {'name':"longshuai",'age':23}>>> print(reply % values)hello longshuai!Your age is 23
字符串格式化方法:format()
使用format()来格式化字符串时,使用在字符串中使用{}
作为占位符,占位符的内容将引用format()中的参数进行替换。可以是位置参数、命名参数或者兼而有之。
看示例就明白了。
# 位置参数>>> template = '{0}, {1} and {2}'>>> template.format('long','shuai','gao')'long, shuai and gao'# 命名参数>>> template = '{name1}, {name2} and {name3}'>>> template.format(name1='long', name2='shuai', name3='gao')'long, shuai and gao'# 混合位置参数、命名参数>>> template = '{name1}, {0} and {name3}'>>> template.format("shuai", name1='long', name3='gao')'long, shuai and gao'
需要注意,format()函数中,位置参数必须放在所有的命名参数之前。例如,下面的会报错:
template.format(name1='long', "shuai", name3='gao')
因为字符串中的占位符是直接引用format中的参数属性的,在占位符处可以进行索引取值、方法调用等操作。例如:
>>> import sys>>> 'My {1[name]} OS is {0.platform}'.format(sys,{"name":"laptop"})'My laptop OS is win32'>>> 'My {config[name]} OS is {sys.platform}'.format(sys=sys,config={'name':'loptop'})'My loptop OS is win32'
但是,在占位符使用索引或切片时,不能使用负数,但可以将负数索引或负数切片放在format的参数中。
>>> s = "hello">>> 'first={0[0]}, last={0[4]}'.format(s)'first=h, last=o'# 下面是错的>>> 'first={0[0]}, last={0[-1]}'.format(s)# 下面是正确的>>> 'first={0[0]}, last={1}'.format(s, s[-1])'first=h, last=o'
format()作为函数,它也能进行参数解包,然后提供给占位符。
>>> s=['a','b','c']>>> '{0}, {1} and {2}'.format(*s)'a, b and c'
在占位符后面加上数值可以表示占用字符宽度。
>>> '{0:10} = {1:10}'.format('abc','def')'abc = def '>>> '{0:10} = {1:10}'.format('abc',123)'abc = 123'>>> '{0:10} = {1:10}'.format('abc',123.456)'abc = 123.456'
使用>
表示右对齐,<
表示左对齐,^
表示居中对齐,并且可以使用0来填充空格。
>>> '{0:>10} = {1:>10}'.format('abc','def')' abc = def'>>> '{0:>10} = {1:<10}'.format('abc','def')' abc = def '>>> '{0:^10} = {1:^10}'.format('abc','def')' abc = def '>>> '{0:10} , {1:<06}'.format('abc','def')'abc , def000'>>> '{0:10} , {1:>06}'.format('abc','def')'abc , 000def'>>> '{0:10} , {1:^06}'.format('abc','def')'abc , 0def00'
可以指定e、f、g类型的浮点数,默认采用g浮点数格式化。例如:
>>> '{0:f}, {1:.2f}, {2:06.2f}'.format(3.14159, 3.14159, 3.14159)'3.141590, 3.14, 003.14'
:.2f
表示保留两位小数,:06.2f
表示最大长度位6字符,左边使用0填充而不是字符串,保留2位小数。
甚至,可以从format()中指定小数位数。
>>> '{0:.{1}f}'.format(1/3, 4)'0.3333'
内置函数format()
除了字符串方法format(),还提供了一个快速格式化单个字符串目标的内置函数format()。
用法示例:
>>> '{0:.2f}'.format(1.2345)'1.23'>>> format(1.2345, '.2f')'1.23'>>> '%.2f' % 1.2345'1.23'