python字符串格式化的幾種方式


1.%格式符

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

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

2.str.format()

name = '李四'
age = 18
# 替換字段用大括號進行標記
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?
# 通過參數來以其他順序引用變量
a3 = "hello, {name}. you are {age1}?".format(age1=age,name=name)
print(a3)    #hello, 李四. you are 18?
# 從字典中讀取數據時還可以使用 **
data = {"name":"張三","age":18}
a4 = "hello, {name}. you are {age}?".format(**data)
print(a4)    #hello, 李四. you are 18?

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

3.f-Strings

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

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.

#可以插入表達式
def sum_a_b(a,b):
    return a + b
a = 1
b = 2
print('求和的結果為' + 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
# ! , : { } ;這些標點不能出現在{} 這里面。
# print(f'{;12}')  # 報錯
# 所以使用lambda 表達式會出現一些問題。
# 解決方式:可將lambda嵌套在圓括號里面解決此問題。
x = 5
print(f'{(lambda x: x*2) (x)}')  # 10

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM