溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

python字符串格式化方式解析

發(fā)布時間:2020-09-20 13:04:26 來源:腳本之家 閱讀:184 作者:Primrose 欄目:開發(fā)技術(shù)

1.%格式符

name = '李四'
age = 18
a = "姓名:%s,年齡:%s"%(name,age)
print(a)   #姓名:李四,年齡:18
​
b = "%(name)s,%(age)s"%{'name':'張三','age':18}
print(b)   #張三,18

這種格式化并不是很好,因?yàn)樗苋唛L并且容易導(dǎo)致錯誤,比如沒有正確顯示元組或字典

2.str.format()

name = '李四'
age = 18
# 替換字段用大括號進(jìn)行標(biāo)記
a1 = "hello, {}. you are {}?".format(name,age)
print(a1)   #hello, 李四. you are 18?
​
# 通過索引來以其他順序引用變量
a2 = "hello, {1}. you are {0}?".format(age,name)
print(a2)  #hello, 李四. you are 18?
​
# 通過參數(shù)來以其他順序引用變量
a3 = "hello, {name}. you are {age1}?".format(age1=age,name=name)
print(a3)  #hello, 李四. you are 18?
​
# 從字典中讀取數(shù)據(jù)時還可以使用 **
data = {"name":"張三","age":18}
a4 = "hello, {name}. you are {age}?".format(**data)
print(a4)  #hello, 李四. you are 18?

在處理多個參數(shù)和更長的字符串時仍然可能非常冗長

3.f-Strings

f-strings 是指以 f 或 F 開頭的字符串,其中以 {} 包含的表達(dá)式會進(jìn)行值替換。

name = '李四'
age = 18
# F 和 f 的簡單使用
b1 = f"hello, {name}. you are {age}?"
b2 = F"hello, {name}. you are {age}?"
print(b1)   # hello, 李四. you are 18?
print(b2)   # hello, 李四. you are 18?

# 字典也可以
teacher = {'name': 'meet', 'age': 18}
msg = f"The teacher is {teacher['name']}, aged {teacher['age']}"
print(msg) # The comedian is meet, aged 18

# 列表也行
l1 = ['meet', 18]
msg = f'姓名:{l1[0]},年齡:{l1[1]}.'
print(msg) # 姓名:meet,年齡:18.

#可以插入表達(dá)式
def sum_a_b(a,b):
  return a + b
a = 1
b = 2
print('求和的結(jié)果為' + f'{sum_a_b(a,b)}')

#多行f 反斜杠
name = 'barry'
age = 18
ajd = 'handsome'

speaker = f'Hi {name}.'\
     f'You are {age} years old.'\
     f'You are a {ajd} guy!'
print(speaker)  #Hi barry.You are 18 years old.You are a handsome guy!
print(f"{You are very \"handsome\"}")   #報(bào)錯


#括號的處理 -->重點(diǎn):兩對為一組
print(f"{{73}}") # {73}
print(f"{{{73}}}") # {73}
print(f"{{{{73}}}}") # {{73}}


m = 21
# ! , : { } ;這些標(biāo)點(diǎn)不能出現(xiàn)在{} 這里面。
# print(f'{;12}') # 報(bào)錯
# 所以使用lambda 表達(dá)式會出現(xiàn)一些問題。
# 解決方式:可將lambda嵌套在圓括號里面解決此問題。
x = 5
print(f'{(lambda x: x*2) (x)}') # 10

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI