Python - 單詞替換



在文字處理中,替換整個字串或字串的一部分是一個非常常見的需求。replace() 方法返回一個字串的副本,其中舊字串的所有出現都被替換為新字串,可以選擇限制替換次數為 max。

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

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

引數

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

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

  • max - 如果提供了可選引數 max,則僅替換前 count 次出現。

此方法返回一個字串的副本,其中所有舊子字串的出現都被替換為新子字串。如果提供了可選引數 max,則僅替換前 count 次出現。

示例

以下示例演示了 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","Tutorialspoint has the best tutorials for learning.")
print (Replacedline)

當我們執行以上程式時,我們得到以下輸出:

Tutorialspoint has the best Tutorials for learning.
廣告

© . All rights reserved.