Python 中的字串方法

已完成

字串是 Python 中最常見的方法類型之一。 您通常需要處理字串,才能從中擷取資訊或使其符合特定格式。 Python 包含幾個旨在執行最常見且實用之轉換的字串方法。

字串方法是 str 型別的一部分。 這表示該方法會以字串變數的形式存在,或直接就是字串的一部分。 例如,方法 .title() 會以初始大寫傳回字串,而且可以直接與字串搭配使用:

print("temperatures and facts about the moon".title())

輸出:Temperatures And Facts About The Moon

而相同的行為和使用模式也會發生在變數上:

heading = "temperatures and facts about the moon"
heading_upper = heading.title()
print(heading_upper)

分割字串

.split() 是一種常見的字串方法。 如果沒有引數,此方法會在每個空格處分割字串。 這麼做會產生一個以空格分隔的單字或數字清單:

temperatures = "Daylight: 260 F Nighttime: -280 F"
temperatures_list = temperatures.split()
print(temperatures_list)

輸出:['Daylight:', '260', 'F', 'Nighttime:', '-280', 'F']

在此範例中,您要處理許多行,因此可以在每一行的最後用 (隱含) 新行字元來分割字串以建立單行:

temperatures = "Daylight: 260 F\n Nighttime: -280 F"
temperatures_list = temperatures.split('\n')
print(temperatures_list)

輸出:['Daylight: 260 F', 'Nighttime: -280 F']

當您需要迴圈來處理或擷取資訊時,或是從文字檔或其他資源載入資料時,這種分割方式就很方便。

搜尋字串

某些字串方法不需要使用迴圈就可以在處理之前尋找內容。 想讓我們假設你有兩個句子在討論不同星球和月球上的氣溫。 不過,您只對與月球相關的溫度感興趣。 也就是說,如果句子中沒有提到月球,就不應該處理它們來擷取資訊。

若要探索字串中是否存在指定的單字、字元或字元群組,最簡單的方式是使用 in 運算子:

print("Moon" in "This text will describe facts and challenges with space travel")

輸出:False

print("Moon" in "This text will describe facts about the Moon")

輸出:True

若要在字串中尋找特定單字的位置,可以使用 .find() 方法:

temperatures = """Saturn has a daytime temperature of -170 degrees Celsius, while Mars has -28 Celsius."""
print(temperatures.find("Moon"))

輸出:-1

.find() 方法在找不到單字時會傳回 -1,找到則會傳回索引 (表示單字在字串中位置的數字)。 如果您要搜尋單字 火星,運作方式如下:

temperatures = """Saturn has a daytime temperature of -170 degrees Celsius, while Mars has -28 Celsius."""
print(temperatures.find("Mars"))

輸出:64

64"Mars" 出現在字串中的位置。

.count() 方法也可以用來搜尋內容,此方法會傳回字串中某個單字出現的總次數:

temperatures = """Saturn has a daytime temperature of -170 degrees Celsius, while Mars has -28 Celsius."""
print(temperatures.count("Mars"))
print(temperatures.count("Moon"))
1
0

Python 中的字串會區分大小寫,這表示 Moonmoon 會被視為不同的單字。 若要進行不區分大小寫的比較,您可以使用 .lower() 方法,將字串中所有字母轉換為小寫:

print("The Moon And The Earth".lower())

輸出:the moon and the earth

.lower() 方法類似,.upper() 字串方法會執行相反的動作,將每個字元轉換成大寫:

print("The Moon And The Earth".upper())

輸出:THE MOON AND THE EARTH

提示

搜尋及檢查內容時,比較穩健的方法是將字串轉為小寫,讓大小寫不會導致相符被排除。 舉例來說,如果您要計算單字 the 出現的次數,此方法不會計算 The 出現的次數,儘管兩者是相同的單字。 您可以使用 .lower() 方法將所有字元變更為小寫。

檢查內容

有的時候,您需要處理文字來擷取呈現方式不規則的資訊。 舉例來說,下列字串會比結構凌亂的段落更容易處理:

temperatures = "Mars Average Temperature: -60 C"

若要擷取火星的平均溫度,您可以使用下列方法:

temperatures = "Mars Average Temperature: -60 C"
parts = temperatures.split(':')
print(parts)
print(parts[-1])
['Mars average temperature', ' -60 C']
' -60 C'

上述程式碼會相信,冒號 (:) 後面的所有內容都是溫度。 此字串會在 : 分割而產生兩個項目的清單。 使用清單上的 [-1] 會回傳最後一個項目,也就是此範例中的溫度。

如果文字不規則,您就無法使用相同的分割方法來取得數值。 您必須迴圈執行所有項目,來檢查其數值是否為特定類型。 Python 擁有可以檢查字串類型的方法:

mars_temperature = "The highest temperature on Mars is about 30 C"
for item in mars_temperature.split():
    if item.isnumeric():
        print(item)

輸出:30

如同 .isnumeric() 方法,.isdecimal() 可以檢查看起來像是小數的字串。

重要

您可能會很訝異,"-70".isnumeric() 居然會傳回 False。 這是因為字串中的所有字元都必須是數值,而虛線 (-) 不是數值。 如果您需要檢查字串中的負數的話,.isnumeric() 方法是沒有用的。

您可以在字串上套用額外的驗證來檢查數值。 若為負數,數字的前方會加上虛線,這樣便可以用 .startswith() 方法來偵測:

print("-60".startswith('-'))

輸出:True

同樣地,.endswith() 方法也可以用來確認字串中最後一個字元:

if "30 C".endswith("C"):
print("This temperature is in Celsius")

輸出:This temperature is in Celsius

轉換文字

還有其他方法可幫助您將文字轉換成其他東西。 到目前為止,您已見過以 C 代表攝氏,以 F 代表華氏的字串。 您可以使用 .replace() 方法來尋找和取代所有出現的特定字元或字元群組:

print("Saturn has a daytime temperature of -170 degrees Celsius, while Mars has -28 Celsius.".replace("Celsius", "C"))

輸出:Saturn has a daytime temperature of -170 degrees C, while Mars has -28 C.

如先前所述,.lower() 是將文字標準化以執行不區分大小寫搜尋的好方法。 我們快速檢查一下,看看是否有討論溫度的文字:

text = "Temperatures on the Moon can vary wildly."
print("temperatures" in text)

輸出:False

text = "Temperatures on the Moon can vary wildly."
print("temperatures" in text.lower())

輸出:True

您可能不需要每次都執行不區分大小寫的驗證,但當文字混合使用大小寫時,將所有字母轉換成小寫會是個好方法。

分割文字並執行轉換之後,您可能需要將所有段落重新組合在一起。 就像 .split() 方法可以分割字元一樣,.join() 方法可以將字元重新組合起來。

.join() 方法需要可反覆執行的物件(例如 Python 清單)做為引數,因此其使用方式與其他字串方法不同:

moon_facts = ["The Moon is drifting away from the Earth.", "On average, the Moon is moving about 4cm every year."]
print(' '.join(moon_facts))

輸出:The Moon is drifting away from the Earth. On average, the Moon is moving about 4cm every year.

在此範例中,會使用 ' ' 用來聯結清單中所有項目。