目录

Python - Word Replacement

替换完整的字符串或字符串的一部分是文本处理中非常常见的要求。 replace()方法返回字符串的副本,其中old的出现次数已替换为new,可选地将替换次数限制为max。

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

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

参数 (Parameters)

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

  • new - 这是新的子字符串,它将替换旧的子字符串。

  • max - 如果给出此可选参数max,则仅替换第一次计数出现次数。

此方法返回字符串的副本,其中所有出现的substring old都替换为new。 如果给出了可选参数max,则仅替换第一个计数出现次数。

例子 (Example)

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

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

结果 (Result)

当我们运行上面的程序时,它会产生以下结果 -

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

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

IoWiki has the best Tutorials for learning.
↑回到顶部↑
WIKI教程 @2018