python字符串格式化方式解析
更新時間:2019年10月19日 09:36:29 作者:Primrose
這篇文章主要介紹了python字符串格式化方式解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
1.%格式符
name = '李四'
age = 18
a = "姓名:%s,年齡:%s"%(name,age)
print(a) #姓名:李四,年齡:18
b = "%(name)s,%(age)s"%{'name':'張三','age':18}
print(b) #張三,18
這種格式化并不是很好,因為它很冗長并且容易導(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\"}") #報錯
#括號的處理 -->重點:兩對為一組
print(f"{{73}}") # {73}
print(f"{{{73}}}") # {73}
print(f"{{{{73}}}}") # {{73}}
m = 21
# ! , : { } ;這些標(biāo)點不能出現(xiàn)在{} 這里面。
# print(f'{;12}') # 報錯
# 所以使用lambda 表達(dá)式會出現(xiàn)一些問題。
# 解決方式:可將lambda嵌套在圓括號里面解決此問題。
x = 5
print(f'{(lambda x: x*2) (x)}') # 10
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
利用Python第三方庫xlwt寫入數(shù)據(jù)到Excel工作表實例代碼
大家應(yīng)該都知道xlwt是python中寫入到excel的庫,下面這篇文章主要給大家介紹了關(guān)于利用Python第三方庫xlwt寫入數(shù)據(jù)到Excel工作表的相關(guān)資料,文中通過實例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-07-07
python3.6連接MySQL和表的創(chuàng)建與刪除實例代碼
這篇文章主要介紹了python3.6連接MySQL和表的創(chuàng)建與刪除實例代碼,具有一定借鑒價值,需要的朋友可以參考下2017-12-12

