一、格式化字元串
在 Python 常見的字元串拼接中,使用 + 號連接字元串,也可以使用 .format() 方法,但是這些方法不如 f-strings(Python3.6+ 版本)來的方便簡潔。
name = "Jack"
age = 25
print(f"My name is {name}, and I am {age} years old.")
上述代碼中,我們使用 f-string 把參數 {name} 和 {age} 插入到字元串中,從而形成需要的結果。當然,也可以在花括弧中進行計算和調用函數。
x = 5
print(f"The value of x squared is {x ** 2}.")
上述代碼中,我們使用 f-string 計算 x 的平方,並插入到字元串中。
二、執行代碼
除了格式化字元串,f-strings 還有一個有用的功能:可以在字元串內部執行代碼表達式。
x = 5
print(f"{x} multiplied by 2 is {x * 2}.")
上述代碼中,我們在使用 f-string 的同時執行了 x * 2 的表達式,並輸出結果。
三、變數名簡潔易讀
相比於其他形式的字元串拼接,f-strings 的最大優勢在於它可以讓變數名更容易閱讀,因為代碼幾乎變得自解釋。
first_name = "Jack"
last_name = "Smith"
age = 25
address = "123 Main St."
formatted = f"{first_name} {last_name} is {age} years old and lives at {address}."
print(formatted)
上述代碼中,我們使用 f-string 把 first_name,last_name,age 和 address 插入到字元串中,從而生成一個簡潔易讀的字元串。
四、可讀性強
相比於其他形式的字元串拼接,f-strings 的最大優勢在於它可以讓變數名更容易閱讀,因為代碼幾乎變得自解釋。
name = "Jack"
age = 25
print(f"My name is {name}, and I am {age} years old.")
上述代碼中,我們使用 f-string 把參數 {name} 和 {age} 插入到字元串中,從而生成一個可讀性更強的字元串。
五、結合函數和方法
f-strings 還可以結合函數和方法來生成所需的字元串。
name = "jack smitH"
print(f"{name.title()} is a user.")
上述代碼中,我們使用 f-string 和 Python 內置的字元串方法 title() 來修改字元串中的大小寫,並生成了一個新的字元串。
原創文章,作者:WHCEK,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/371183.html