Pythonformat字串格式化函式的使用

2022-09-26 11:45:22 字數 2493 閱讀 5089

目錄

從python2.6開始,新增了str.format(),它增強了字串格式化的功能。基本語法是通過{}和:來代替以前的%程式設計客棧佔位符。

字串格式符號用法如下

舉個例子:

name = 'sugar'

age = 21

print("his name is %s, and he is %d year old." %(name, age))

結果his name is sugar, and he is 21 year old.

其他格式化輔助操作指令如下,其中用的比較多的就是使用0來補零,和控制小數字數的.

舉個例子:

price = 23.1999

obj = 'milk'

print("the %s's price is %03f" %(obj, price)) # 前面補三個零

print("the %s's price is %3.0f" %(obj, price)) # 最小總佔位長度為3,控制輸出0個小數

print("the %s's price is %3.3f" %(obj, price)) # 最小總佔位長度為3,控制輸出3個小數

print("the %s's price is %5.4f" %(obj, price)) # 最小總佔位長度為5,控制輸出4個小數

結果:the milk's price is 23.199900

the milk's price is  23

the milk's price is 23.200

the milk's price is 23.1999

字串format格式化的四種方式

格式:string{}.format(x1, x2)

舉個例子

price = 23.1999

obj = 'milk'

print("the {}'s price is {}".format(obj, price))

結果如下

the milk's price is 23.1999

格式:string.format(x1, x2)

舉個例子

price = 23.1999

obj = 'milk'

print("the 's price is ".format(obj, price))

結果如下

the milk's price is 23.1999

其實這種方式就相當於前兩種使用程式設計客棧預設位置和使用指定位置的方式,只不過這裡需要使用*對列表進行解包,舉個例子

price = 23.1999

obj = 'milk'

info = [obj, price]

print("the {}'s price is {}".format(*info)) # 對info進行解包

結果如下

the milk's price is 23.1999

格式:string(key).format(key=value)

舉個例子,當然也可以用**對字典進行解包

price = 23.1999

obj = 'milk'

print("the 's price is ".format(name=obj, pri=price))

# 更進一步,對字典進行解包

dic =

print("the 's price is ".format(**dic))

結果如下

the milk's price is 23.1999

the milk's price is 23.1999

需要注意的是,在:冒號後面指定需要填充的內容,可以使用上述4種格式化方式來對文字格式進行控制,舉個例子

price = 23.1999

obj = 'bread'

print(yldpeqrdtd"the {}'s price is ".format(obj, price)) # 使用預設位置方式,保留兩位小數

print("the 's price is ".format(obj, price)) # 使用指定位置方式,保留兩位小數

print("the 's price is ".format(name=obj, price=price)) # 使用字典方式,保留兩位小數

li = [obj, price]

print("the {}'s price is ".format(*li)) # 使用列表解包的方式,保留兩位小數

info =

print("the 's price is ".format(**info)) # 使用字典解包的方式,保留兩位小數

結果如下

the bread's price is 23.20

the bread's price is 23.20

the bread's price is 23.20

the bread's p程式設計客棧rice is 23.20

the bread's price is 23.20

pythonformat格式字串

語法 它通過 和 來代替 注意 字串的format函式可以接受無限個引數,位置可以不按順序,可以不用或者用多次,不過2.6不能為空 2.7才可以。通過位置 in 1 format kzc 18 out 1 kzc,18 in 2 format kzc 18 out 2 kzc,18 in 3 for...

python format格式化字串

你可以用字串的format方法來格式化輸出字串。比如 print we are the who say format knights ni we arethe knights whosay ni 括號內的字元 稱為格式字段 被替換的物件。括號中的數字是指替換的位置,裡面的數字,比如0,1表示替換元組...

Python format格式化字串

python中內建的 操作符可用於格式化字串操作,控制字串的呈現格式。python中還有其他的格式化字串的方式,但 操作符的使用是最方便的。另外python還有乙個更強大的字串處理函式 也就是我們要說的 str.format 語法 通過 符號來代替 符號 它有著豐富的的 格式限定符 語法是 中帶 號...