python中替换函数是replace(),该函数语法格式为:“str.replace(old, new[, max])”,它主要是将字符串中的旧字符串替换成新字符串,如果指定第三个参数max,则替换不超过max次。
具体使用步骤:
1、首先打开python编辑器,新建一个python项目。
2、在python项目中定义一个字符串。
str = "this is string example....wow!!! this is really string";
3、最后再通过replace()函数进行替换字符串即可。
print str.replace("is", "was");
完整示例代码:
#!/usr/bin/python
#www.yisu.com
str = "this is string example....wow!!! this is really string";
print str.replace("is", "was");
print str.replace("is", "was", 3);
输出结果:
thwas was string example....wow!!! thwas was really string
thwas was string example....wow!!! thwas is really string
扩展知识:
strip() #删除指定字符串函数
re.sub() #通过正则表达式替换