如何使用Python在文件中搜索和替换文本?
在Python模块re中有re.sub()方法,可以搜索模式并替换为新的子字符串。如果未找到模式,则返回未更改的字符串。
re.sub()方法的语法如下:
re.sub(pattern, repl, string):
例如,在以下代码中,我们搜索“India”,并将其替换为“the World”在字符串“TP is most popular Tutorials site of India”中
阅读更多:Python 教程
例子
result=re.sub(r'India', 'the World', 'TP is the most popular Tutorials site of India')
print result
输出
TP is the most popular Tutorials site of the World
极客教程