# 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
总结:正则替换的方法更为强大,通过正则的编辑可实现多个不同内容同时替换