python字符串格式化输出

python中有两种格式化输出字符串的方式:格式化表达式、format()方法。固然,还有一个简化操做的内置format()函数。python

它们绝大部分功能都是重复的,熟悉printf的能够考虑使用格式化表达式,不然使用format()更友好些,由于它像处理函数参数同样,但format()有时候可能写的要更复杂。函数

格式化表达式

格式化表达式相似于printf的风格,在字符串中使用%做为占位符。本文只是介绍python中的一些特性,若有须要请自行搜索printf用法。code

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

字符串和替换目标之间也使用%分隔,且替换部分能够有多个(使用括号包围),能够使用变量。orm

替换目标还能够使用字典,这时在字符串中的%占位符能够以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()中的参数进行替换。能够是位置参数、命名参数或者兼而有之。it

看示例就明白了。ast

# 位置参数
>>> 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()函数中,位置参数必须放在全部的命名参数以前。例如,下面的会报错:form

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'
相关文章
相关标签/搜索