这篇文章将为大家详细讲解有关python如何替换字符串的内容,对于新手来说操作方便快捷,我觉得挺实用的,所有给大家让大家做个参考,希望大家阅读完这篇文章之后能有所收获,下面让我们一起来了解吧!

python如何替换字符串的内容? 一个函数轻松实现!

需要用到一个函数叫做replace(),它是作用就是跟英汉译一样,替换的意思,把一个旧的字符替换成一个你需要的新字符,其中指定第三个参数max的话,表示的是字符串替换次数不超过max次。

replace()函数的基本语法:

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

上面例子参数中old是表示会被替换的一个旧字符串。new 表示的是一个新的字符串用于替换旧的old子字符串。max 是表示一个可选字符串, 替换次数不超过 max 次。

返回值:返回字符串中的 old(旧字符串) 替换成 new(新字符串)后生成的新字符串,如果指定第三个参数max,则替换次数不超过 max 次。

举个例子来说明replace()函数的使用方法:

实例1:

str = "this is a beautify girl....wow!!! this is a handsome boy!!!";
print str.replace("is", "was");
print str.replace("is", "was", 3);
print str.replace("is", "was", 2);

以上实例输出结果如下:

this was a beautify girl....wow!!! this was a handsome boy!!!

this was a beautify girl....wow!!! this is a handsome boy!!!

this is a beautify girl....wow!!! this is a handsome boy!!!

实例2:

以下方法也可以实现代码替换:

def modify_text():
     with open('hh.txt', "r+") as f:
         read_data = f.read()
         f.seek(0)
         f.truncate()   #清空文件
         f.write(read_data.replace('hello', 'hello boy'))
 if __name__ == '__main__':
     modify_text()

让我们来看看运行前后结果对比

运行前文件:

hello, hello, hello

运行后文件:

hello boy, hello boy, hello boy

关于python如何替换字符串的内容就分享到这里了,希望以上内容可以帮助到大家学到更多知识。想要了解更多相关知识,可以继续关注哦!

更多python相关文章请访问分类:python

【版权声明】本文图文出自大盘站@dapan.cc,转载请注明出处!