Python – 替换单词

Python – 替换单词

在文本处理中,完全替换字符串或部分替换字符串是非常频繁的需求。replace() 方法返回一个字符串的拷贝,在其中使用新的字符串 new 替换了所有旧的字符串 old,可选择限制更换的次数 max。

下面是 replace() 方法的语法−

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

参数

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

  • new − 新字符串,它将替换旧字符串。

  • max − 如果给出了这个可选参数 max,那么只替换前 count 次出现。

此方法返回所有子字符串 old 的出现均已被替换为 new 的字符串的拷贝。如果给定了可选参数 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.

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程