Python 中的字串基本知識

已完成

雖然 Python 中的字串看起來很簡單且直接,但務必要掌握的字串規則就有點複雜。 了解規則可協助您避免在修改值或格式化文字時發生字串行為意外。

簡單的字串

在本課程單元的範例中,您有一個關於指派給變數的月球事實,像是這樣:

fact = "The Moon has no atmosphere."
print(fact)

輸出會顯示文字已指派給變數: The Moon has no atmosphere.

字串的不變性

在 Python 中,字串不可變。 也就是說,其不得變更。 此字串類型屬性可能會令人意外,因為 Python 不會在您更改字串時發出錯誤。

您必須將另一個事實 (句子) 新增至指派給變數的單一事實。 新增第二個事實似乎會改變變數,如下列範例所示:

fact = "The Moon has no atmosphere."
fact + "No sound can be heard on the Moon."

您可能會預期輸出為: The Moon has no atmosphere.No sound can be heard on the Moon.

雖然我們似乎已修改變數 fact,但快速檢查值會顯示原始值未變更:

fact = "The Moon has no atmosphere."
fact + "No sound can be heard on the Moon."
print(fact)

輸出:The Moon has no atmosphere.

訣竅是您必須使用傳回值。 當您新增字串時,Python 不會修改任何字串,但會傳回「新的」字串作為結果。 若要保留此新結果,請將其指派給新的變數:

fact = "The Moon has no atmosphere."
two_facts = fact + "No sound can be heard on the Moon."
print(two_facts)

輸出:The Moon has no atmosphere.No sound can be heard on the Moon.

字串上的作業一律會產生新的字串作為結果。

關於使用引號

您可以用單引號、雙引號或三重引號括住 Python 字串。 雖然您可以交替使用這些引號,但最好在專案中一致地使用一種類型。 例如,下列字串均使用雙引號:

moon_radius = "The Moon has a radius of 1,080 miles."

然而,當字串包含也以引號括住的文字、數字或特殊字元 (「子字串」) 時,您就應該使用不同的樣式。 例如,若子字串使用雙引號,請將整個字串括在單引號中,如下所示:

'The "near side" is the part of the Moon that faces the Earth.'

同樣地,若字串中的任何位置有單引號 (或如下列範例中 Moon's 的單引號),請以雙引號括住整個字串:

"We only see about 60% of the Moon's surface."

無法替代單引號與雙引號可能會導致 Python 解譯器引發語法錯誤,如下所示:

'We only see about 60% of the Moon's surface.'
  File "<stdin>", line 1
    'We only see about 60% of the Moon's surface.'
                                       ^
SyntaxError: invalid syntax

當文字具有單引號與雙引號的組合時,您可以使用三重引號來防止解譯器發生問題:

"""We only see about 60% of the Moon's surface, this is known as the "near side"."""

多行文字

有幾種不同的方式可將多行文字定義為單一變數。 最常見的方式如下:

  • 使用新行字元 (\n)。
  • 使用三重引號 (""")。

當您列印輸出時,新行字元會將文字分隔成多行:

multiline = "Facts about the Moon:\n There is no atmosphere.\n There is no sound."
print(multiline)
Facts about the Moon:
 There is no atmosphere.
 There is no sound.

您可以使用三重引號來達成相同的結果:

multiline = """Facts about the Moon:
 There is no atmosphere. 
 There is no sound."""
print(multiline)