f-string 是 Python 3.6 中引入的一種新的字串格式化方式,全名是 Formatted String Literals。它的主要目的是為了使字串內的變數插值更加容易和直觀。

f-string 的使用方式是在字串前加上字母 f 或 F,然後在字串內部的大括號 {} 中放入需要插入的變數或表達式,如下例:

1
2
3
name = "Alice"
age = 25
print(f"My name is {name} and I'm {age} years old.")

輸出結果將是:

1
My name is Alice and I'm 25 years old.

在這個例子中,{name}將被替換成變數 name 的值,{age}將被替換成變數 age 的值。

此外,f-string 還支援在大括號內寫入任意有效的 Python 表達式,並將其計算結果插入到字串中。例如:

1
2
3
a = 5
b = 10
print(f"Five plus ten is {a + b}, not {2 * (a + b)}.")

輸出結果將是:

1
Five plus ten is 15, not 30.

在這個例子中,{a + b}將被替換成 a 和 b 的和,{2 * (a + b)}將被替換成 2 * (a + b)的結果。

使用 f-string,我們可以更方便地在字串中插入變數和表達式,並將其計算結果轉換為字串。


作者: 微風