replace函数可以基于某字符串将其某子串替换成其他子串,返回值是一个新的字符串,意思是原字符串不变,而是新产生一个字符串。语法格式如下:
S.replace(old, new[, count]) -> string
old是要被替换的,new是要替换成的,而count参数的意思是从左至右替换几处。
replace示例
s = "python"
s1 = s.replace('p', 'P')
print s
print s1
s = "python "
s = s * 5
s2 = s.replace('p', 'J', 3)
print s2
程序的执行结果:
python
Python
Jython Jython Jython python python
代码里的语句s2 = s.replace('p', 'J', 3)的作用是替换s字符串里前3次出现的子串"p"为"J"新产生s2字符串。