python——replace函数

replace就像它的中文翻译,替换的意思,可以输入help(replace)看一下它的用法
在这里插入图片描述

replace(self, old, new, count=-1, /),这个就是replace的基本用法,old就是指要替换的字符串,,new就是产生的新的字符串,count是替换的次数,如果指定第三个参数max,则替换次数不超过max次(将旧的字符串用心的字符串替换不超过max次)。

举个例子:
(1)下面的string定义了有三个apple,当我们未传入count的参数是,默认将所有的apple替换成a

string = 'apple banana cat dog apple egg apple'

result = string.replace('apple','a')

print(result)

输出结果为:a banana cat dog a egg a

(2)当我们给count加个参数时,它会按照这个参数来替换

string = 'apple banana cat dog apple egg apple'

result = string.replace('apple','a',2)

print(result)

输出结果为:a banana cat dog apple egg apple,可以看到替换了两个apple,感兴趣的朋友可以尝试更多的用法

正在尝试写博客,把会的分享给你们,如有写的不好的地方,希望指点一下,喜欢的朋友们请点个赞,谢谢!

猜你喜欢

转载自blog.csdn.net/Woo_home/article/details/88596802