str.replace(old,new[max]) replace() 方法把字符串中的 old(旧字符串) 替换成
new(新字符串),如果指定第三个参数max,则替换不超过 max 次。 re.sub(’\d+’,‘666’,inputStr)
将inputStr中的数字替换成666 \d:匹配任意一个数字 包括[0-9]和其他数字字符 \D:(\d)的相反
import re
inputStr = 'hello 121 world 999'
print(inputStr)
replaceStr = inputStr.replace('121','666')
print(replaceStr)
replaceStr = re.sub('\d+',' 88888 ',inputStr)
print(replaceStr)
replaceStr = re.sub('\D+',' 1111 ',inputStr)
print(replaceStr)
结果是:
hello 121 world 999
hello 666 world 999
hello 88888 world 88888
1111 121 1111 999