python字符串格式化方式解析
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(zhǎng)并且容易導(dǎo)致錯(cuò)誤,比如沒有正確顯示元組或字典
2.str.format()
name = '李四' age = 18 # 替換字段用大括號(hào)進(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ù)時(shí)還可以使用 ** data = {"name":"張三","age":18} a4 = "hello, {name}. you are {age}?".format(**data) print(a4) #hello, 李四. you are 18?
在處理多個(gè)參數(shù)和更長(zhǎng)的字符串時(shí)仍然可能非常冗長(zhǎng)
3.f-Strings
f-strings 是指以 f 或 F 開頭的字符串,其中以 {} 包含的表達(dá)式會(huì)進(jìn)行值替換。
name = '李四' age = 18 # F 和 f 的簡(jiǎn)單使用 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)錯(cuò) #括號(hào)的處理 -->重點(diǎn):兩對(duì)為一組 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)錯(cuò) # 所以使用lambda 表達(dá)式會(huì)出現(xiàn)一些問題。 # 解決方式:可將lambda嵌套在圓括號(hào)里面解決此問題。 x = 5 print(f'{(lambda x: x*2) (x)}') # 10
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python實(shí)現(xiàn)密碼強(qiáng)度校驗(yàn)
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)密碼強(qiáng)度校驗(yàn),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-03-03Python多線程批量采集圖片的代碼實(shí)現(xiàn)
這篇文章主要給大家介紹了Python多線程批量采集圖片的代碼實(shí)現(xiàn),文中通過代碼示例講解的非常詳細(xì),具有一定的參考價(jià)值,需要的朋友可以參考下2024-05-05利用Python第三方庫(kù)xlwt寫入數(shù)據(jù)到Excel工作表實(shí)例代碼
大家應(yīng)該都知道xlwt是python中寫入到excel的庫(kù),下面這篇文章主要給大家介紹了關(guān)于利用Python第三方庫(kù)xlwt寫入數(shù)據(jù)到Excel工作表的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-07-07windows中python實(shí)現(xiàn)自動(dòng)化部署
本文主要介紹了windows中python實(shí)現(xiàn)自動(dòng)化部署,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08python3.6連接MySQL和表的創(chuàng)建與刪除實(shí)例代碼
這篇文章主要介紹了python3.6連接MySQL和表的創(chuàng)建與刪除實(shí)例代碼,具有一定借鑒價(jià)值,需要的朋友可以參考下2017-12-12