Python 中的字串格式

已完成

除了轉換文字並執行比對和搜尋等基本作業外,在呈現資訊時也必須將文字格式化。 使用 Python 呈現文字資訊最簡單的方式是使用 print() 函式。 您會發現,將變數和其他資料結構中的資訊轉為 print() 可使用的字串非常重要。

在本單元中,您將了解使用 Python 在文字中納入變數值的幾種有效方法。

百分比符號 (%) 格式設定

字串中變數的預留位置為 %s。 在字串之後,請使用另一個 % 字元,後面接著變數名稱。 下列範例示範如何使用 % 字元來格式化:

mass_percentage = "1/6"
print("On the Moon, you would weigh about %s of your weight on Earth." % mass_percentage)

輸出:On the Moon, you would weigh about 1/6 of your weight on Earth.

使用多個值會變更語法,因為其需要用括弧來包圍傳入的變數:

print("""Both sides of the %s get the same amount of sunlight, but only one side is seen from %s because the %s rotates around its own axis when it orbits %s.""" % ("Moon", "Earth", "Moon", "Earth"))

輸出:Both sides of the Moon get the same amount of sunlight, but only one side is seen from Earth because the Moon rotates around its own axis when it orbits Earth.

提示

雖然此方法仍然是將字串格式化的有效方法,但是當您處理多個變數時,可能會導致程式碼中的錯誤,並降低明確性。 本單元所述的其他兩個格式化選項皆更適合此用途。

format() 方法

.format() 方法會使用大括弧 ({}) 做為字串內的預留位置,並使用變數指派來取代文字。

mass_percentage = "1/6"
print("On the Moon, you would weigh about {} of your weight on Earth.".format(mass_percentage))

輸出:On the Moon, you would weigh about 1/6 of your weight on Earth.

您不需要多次指派重複的變數,使程式碼更為精簡,因為需要指派的變數較少:

mass_percentage = "1/6"
print("""You are lighter on the {0}, because on the {0} you would weigh about {1} of your weight on Earth.""".format("Moon", mass_percentage))

輸出:You are lighter on the Moon, because on the Moon you would weigh about 1/6 of your weight on Earth.

使用數字替代使用空括號。 {0} 表示將第一個 (索引零) 引數用於 .format(),在此案例中為 Moon{0} 可以簡單重複運作,但會減少可讀性。 若要改善可讀性,請在 .format() 中使用關鍵字引數,然後在大括弧中參考相同的引數:

mass_percentage = "1/6"
print("""You are lighter on the {moon}, because on the {moon} you would weigh about {mass} of your weight on Earth.""".format(moon="Moon", mass=mass_percentage))

輸出:You are lighter on the Moon, because on the Moon you would weigh about 1/6 of your weight on Earth.

關於 f-string

從 Python 3.6 版開始,可以使用 f-strings。 這些字串看起來像範本,並使用程式碼中的變數名稱。 在上述範例中使用 f-string,如下所示:

print(f"On the Moon, you would weigh about {mass_percentage} of your weight on Earth.")

輸出:On the Moon, you would weigh about 1/6 of your weight on Earth.

變數會以大括弧括住,而且字串「必須」使用 f 前置詞。

f-string 字串除了比其他格式化選項更為精簡以外,還可以在大括弧內使用運算式。 這些運算式可以是函式或直接作業。 例如,如果您想要以具有一個小數位數的百分比來表示 1/6 值,您可以直接使用 round() 函式:

print(round(100/6, 1))

輸出:16.7

使用 f-string 時,您不需要事先將值指派給變數:

print(f"On the Moon, you would weigh about {round(100/6, 1)}% of your weight on Earth.")

輸出:On the Moon, you would weigh about 16.7% of your weight on Earth.

使用運算式不需要函式呼叫。 任何字串方法也都可用。 例如,字串可能會強制以特定的大小寫來建立標題:

subject = "interesting facts about the moon"
heading = f"{subject.title()}"
print(heading)

輸出:Interesting Facts About The Moon