Python 字串 replace() 方法



Python 字串 replace() 方法用於替換字串中所有出現的某個子字串為另一個子字串。此方法用於透過替換原始字串的某些部分來建立另一個字串,其核心內容可能保持不變。

例如,在即時應用程式中,此方法可用於一次性替換文件中多個相同的拼寫錯誤。

此 replace() 方法還可以替換字串中選定的子字串出現次數,而不是全部替換。

語法

以下是 Python 字串 replace() 方法的語法:

str.replace(old, new[, count])

引數

  • old - 要替換的舊子字串。

  • new - 新子字串,將替換舊子字串。

  • count - 如果給出此可選引數 count,則僅替換前 count 次出現。

返回值

此方法返回字串的副本,其中所有出現的子字串 old 都被替換為 new。如果給出可選引數 count,則僅替換前 count 次出現。

示例

以下示例顯示了 Python 字串 replace() 方法的用法。

str = "Welcome to Tutorialspoint"
str_replace = str.replace("o", "0")
print("String after replacing: " + str_replace)

執行以上程式時,將產生以下結果:

String after replacing: Welc0me t0 Tut0rialsp0int

示例

當我們連同可選的 count 引數一起傳遞子字串引數時,該方法僅替換字串中前 count 次出現的子字串。

在下面的示例中,建立了輸入字串,並且該方法接受三個引數:兩個子字串和一個 count 值。返回值將是在替換前 count 個出現次數後獲得的字串。

str = "Fred fed Ted bread and Ted fed Fred bread."
strreplace = str.replace("Ted", "xx", 1)
print("String after replacing: " + strreplace)

執行以上程式時,將產生以下結果:

String after replacing: Fred fed xx bread and Ted fed Fred bread.

示例

當我們將兩個子字串和 count = 0 作為引數傳遞給該方法時,原始字串將作為結果返回。

在下面的示例中,我們建立了一個字串 "Learn Python from Tutorialspoint",並嘗試使用 replace() 方法將單詞 "Python" 替換為 "Java"。但是,由於我們將計數傳遞為 0,因此此方法不會修改當前字串,而是返回原始值 ("Learn Python from Tutorialspoint")。

str = "Learn Python from Tutorialspoint"
strreplace = str.replace("Python", "Java", 0)
print("String after replacing: " + strreplace)

如果執行上面的程式,輸出將顯示為 -

String after replacing: Learn Python from Tutorialspoint
python_strings.htm
廣告