如何使用Python在文件中搜索和替换文本?

如何使用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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程