# 1、用字符串本身的replace方法
# 复制代码代码如下:
a='hello,world,world'
print(a.replace('world','python',1)) #1:最高代替次数
#输出的结果是hello,python,world
# 2、用正则表达式来完成替换:
# 复制代码代码如下:
import re
# strinfo=re.compile('world')
# b=strinfo.sub('python',a)
strinfo=re.compile('world')
b=re.sub(strinfo,'python',a) #两种写法都可以
print(b)
# 输出的结果也是hello,python,python
总结:正则替换的方法更为强大,通过正则的编辑可实现多个不同内容同时替换
本文介绍了两种在Python中进行字符串替换的方法:使用字符串自带的replace方法和利用正则表达式。通过实例对比了这两种方法的特点,指出正则表达式方法在替换操作上更为灵活和强大。
573

被折叠的 条评论
为什么被折叠?



