python字串格式化的幾種方式

2022-06-23 05:57:10 字數 2236 閱讀 4895

name = '李四'

age = 18a = "

姓名:%s,年齡:%s

"%(name,age)

print(a) #

姓名:李四,年齡:18

​b = "

%(name)s,%(age)s

"%print(b) #

張三,18

這種格式化並不是很好,因為它很冗長並且容易導致錯誤,比如沒有正確顯示元組或字典

name = '李四'

age = 18

#替換欄位用大括號進行標記

a1 = "

hello, {}. you are {}?

".format(name,age)

print(a1) #

hello, 李四. you are 18?​#

通過索引來以其他順序引用變數

a2 = "

hello, . you are ?

".format(age,name)

print(a2) #

hello, 李四. you are 18?​#

通過引數來以其他順序引用變數

a3 = "

hello, . you are ?

".format(age1=age,name=name)

print(a3) #

hello, 李四. you are 18?​#

從字典中讀取資料時還可以使用 **

data =

a4 = "

hello, . you are ?

".format(**data)

print(a4) #

hello, 李四. you are 18?

在處理多個引數和更長的字串時仍然可能非常冗長

f-strings 是指以 f 或 f 開頭的字串,其中以 {} 包含的表示式會進行值替換。

name = '李四'

age = 18

#f 和 f 的簡單使用

b1 = f"

hello, . you are ?

"b2 = f"

hello, . you are ?

"print(b1) #

hello, 李四. you are 18?

print(b2) #

hello, 李四. you are 18?

#字典也可以

teacher =

msg = f"

the teacher is , aged

"print(msg) #

the comedian is meet, aged 18

#列表也行

l1 = ['

meet

', 18]

msg = f'

姓名:,年齡:.

'print(msg) #

姓名:meet,年齡:18.

#可以插入表示式

defsum_a_b(a,b):

return a +b

a = 1b = 2

print('

求和的結果為

' + f'')

#多行f 反斜槓

name = '

barry

'age = 18ajd = '

handsome

'speaker = f'

hi .'\

f'you are years old.'\

f'you are a guy!

'print(speaker) #

hi barry.you are 18 years old.you are a handsome guy!

print(f"

") #報錯#

括號的處理 -->重點:兩對為一組

print(f"

}") #

print(f"

}}") #

print(f"

}}}") #

}m = 21

#! , : ;這些標點不能出現在{} 這裡面。

#print(f'') # 報錯

#所以使用lambda 表示式會出現一些問題。

#解決方式:可將lambda巢狀在圓括號裡面解決此問題。

x = 5

print(f'

') #

10

Python幾種格式化字串的方式

方式一 百分號 方式,類c的printf,需要分別不同型別。1 匿名tuple。推薦在引數少時用 1 2 姓名 s,年齡 d walker 99 姓名 walker,年齡 99 2 命名dict,字典的key可以重用。1 2 姓名 name s,年齡 age d,工齡 age d 姓名 walker...

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中的一致。右邊的 值組 如果有兩個及以上的值則需要用小括號括起來,中間用短號隔開。重點來看左邊的部分。左邊部分的最簡單...