python字串格式化

2021-08-16 20:24:02 字數 2021 閱讀 2827

python擁有兩種字串格式化型別%和format()

語法

%[(key)][flags][width].[precision]typecode
裡的都為可選項。

key:字典的鍵

flags:符號可以使用' '(空格,不保留正號右對齊)、'+'(保留正號右對齊)、'-'(不保留正號左對齊)、'0'(缺位補零)。

(注:flags需要和width配合使用,用來格式化字串的位置)

width:字串長度(若小於原長度,則會全部輸出。若大於不足為用空格補齊。)

precision:小數字精度。僅對數值型變數有效。

typecode:格式化模式。(常見的%d,%s等)

%的方法可以傳實值、元組、字典等。(與c中的字串格式化很像)

下面給出幾個例項

a = "hello world"

b=c = 3.1415926

print("%(name)s is %(age)d years old and he says "%b+"%s"%a) #(key) 為字典的key

print("%+10.3f"%c) #右對齊

print('%s %s'%(a,a)) #利用元組拼接字串

jack is 19 years old and he says hello world

+3.142

hello world hello world

語法:

[[fill]align][flags][#][0][width][,][.precision][type]
format()的使用方式是str.format(需要格式化的字元),str中表示格式化方式

fill:填充字元,同樣需要與width連用,當填充字元不為0或者' '(空格)時需要與align連用

align:對齊方式《左對齊,>右對齊,^居中,=右對齊僅對數字有效

flags:符號,同上。

#:僅對二進位制、八進位制、十六進製制有效,顯示其字首。

,:十進位制千分位分隔符。

width、type與precision同上

下面給幾個例子

a=

b=[100,'hello']

c=5.20

d=('jack',18)

e=8000

print("".format(**a)) #當傳入的值得字典時需要在字典前加**

print("++".format(*b)) #當傳入列表時需要在列別前加*

print("".format(c))                                          #精度不足時僅輸出有效數字

print("name is and he is years old".format(d[0],d[1]))       #可用位置傳參

print("".format(e))                                       #16進製制輸出

****jeffey

---hello++100

00000005.2

name is jack and he is 18 years old

0x1f40

Python 字串格式化

字串格式化 s 格式化為字串 format hello,s.s enough for ya?values world hot print format values hello,world.hot enough for ya?f 格式化為實數 浮點數 format pi with three dec...

python字串格式化

字串的格式化 在python中也有類似於c中的printf 的格式輸出標記。在python中格式化輸出字串使用的是 運算子,通用的形式為 其中,左邊部分的 格式標記字串 可以完全和c中的一致。右邊的 值組 如果有兩個及以上的值則需要用小括號括起來,中間用短號隔開。重點來看左邊的部分。左邊部分的最簡單...

Python字串格式化

字串的格式化 在python中也有類似於c中的printf 的格式輸出標記。在python中格式化輸出字串使用的是 運算子,通用的形式為 其中,左邊部分的 格式標記字串 可以完全和c中的一致。右邊的 值組 如果有兩個及以上的值則需要用小括號括起來,中間用短號隔開。重點來看左邊的部分。左邊部分的最簡單...