📌  相关文章
📜  Python单词替换

📅  最后修改于: 2020-11-06 06:18:23             🧑  作者: Mango


替换整个字符串或部分字符串是文本处理中非常常见的要求。 replace()方法返回字符串的副本,在该字符串中,旧的出现已被新的替换,可以选择将替换次数限制为最大。

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

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

参量

  • old-这是要替换的旧子字符串。

  • 新的-这是一个新的子串,这将取代旧的字符串。

  • 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","Tutorialspoint has the best tutorials for learning.")
print (Replacedline)

当我们运行上面的程序时,我们得到以下输出-

Tutorialspoint has the best Tutorials for learning.