替換完整的字符串或字符串的一部分是文本處理中非常常見的要求。 replace()方法返回字符串的副本,其中old的出現(xiàn)次數(shù)替換為new,可選地將替換次數(shù)限制為max。
以下是replace()方法的語法 -
str.replace(old, new[, max])
old - 這是要替換的舊子字符串。new - 這是新的子字符串,它將替換舊的子字符串。max - 如果給出此可選參數(shù)max,則僅替換第一次計(jì)數(shù)出現(xiàn)次數(shù)。此方法返回字符串的副本,子字符串所有出現(xiàn)的old都替換為new。 如果給出了可選參數(shù)max,則僅替換第一個(gè)計(jì)數(shù)出現(xiàn)次數(shù)。
示例
以下示例顯示了replace()方法的用法。
str = "this is string example....wow!!! this is really string"
print (str.replace("is", "was"))
print (str.replace("is", "was", 3))
當(dāng)運(yùn)行上面的程序時(shí),它會(huì)產(chǎn)生以下結(jié)果 -
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","Tutorialyiibai has the best tutorials for learning.")
print (Replacedline)
當(dāng)運(yùn)行上面的程序時(shí),我們得到以下輸出 -
Tutorialyiibai has the best Yiibai for learning.