python字串格式化輸出

駿馬金龍發表於2018-12-18

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`

相關文章