【Python 3.6.1】replace()方法
一、描述
replace() 方法:将字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。
二、语法
1 |
str.replace(old, new[, max]) |
old:被替换的字符串
new:替换被替换的字符串
max:【可选】,最多替换的次数,默认全部替换
三、测试
1 2 3 4 5 6 7 |
# 中文逗号替换为英文逗号 >>> s1 = 'a,b,c,d,e,f,g' >>> print (s1) a,b,c,d,e,f,g >>> print (s1.replace(',',',')) a,b,c,d,e,f,g >>> |
1 2 3 4 5 6 |
# 中文逗号替换成#号,替换前3个 >>> print (s1) a,b,c,d,e,f,g >>> print (s1.replace(',','#',3) ) a#b#c#d,e,f,g >>> |