python字符串替换方法

python yekong 1063℃

replace功能

将字符串中旧元素替换为新元素,并能指定替换的数量

replace用法

newstr = string.replace(old, new, max)
参数:
old :被替换的元素,
new :替代old的新元素,
max:可选,代表替换几个,默认全部替换全部匹配的old元素

str = 'wanjunshijie.com'
newstr = str.replace('wan', 'www.wan')
print(newstr)
输出结果
www.wanjunshijie.com
str = 'wanjunshijie.com'
newstr = str.replace('i', 's',2)
print(newstr)
输出结果
wanjunshsjse.com
str = 'wanjunshsjse.com'
newstr = str.replace('wan', 'www.wan').replace('s', 'i',2)
print(newstr)
输出结果
www.wanjunshijie.com
喜欢 (0)