單詞替換

替換完整的字串或字串的一部分是文本處理中非常常見的要求。 replace()方法返回字串的副本,其中old的出現次數替換為new,可選地將替換次數限制為max

以下是replace()方法的語法 -

str.replace(old, new[, max])
  • old - 這是要替換的舊子字串。
  • new - 這是新的子字串,它將替換舊的子字串。
  • max - 如果給出此可選參數max,則僅替換第一次計數出現次數。

此方法返回字串的副本,子字串所有出現的old都替換為new。 如果給出了可選參數max,則僅替換第一個計數出現次數。

示例

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

str = "this is string example....wow!!! this is really string"
print (str.replace("is", "was"))
print (str.replace("is", "was", 3))

當運行上面的程式時,它會產生以下結果 -

thwas was string example....wow!!! thwas was really string
thwas was string example....wow!!! thwas is really string

替換忽略大小寫

import re
sourceline  = re.compile("Tutor", re.IGNORECASE)

Replacedline  = sourceline.sub("Tutor","Tutorialzaixian has the best tutorials for learning.")
print (Replacedline)

當運行上面的程式時,我們得到以下輸出 -

Tutorialzaixian has the best zaixian for learning.

上一篇: 文本翻譯 下一篇: 拼寫檢查