Python字符串replace()
方法返回一个字符串的副本,其中出现的旧字符(old
)已被替换为新的(new
)字符串,可选地将替换数限制为最大值 - max
。
语法
以下是replace()
方法的语法 -
str.replace(old, new[, max])
参数
- old - 这是要被替换的旧的子字符串。
- new - 这是新的子字符串,它将替换旧的子字符串。
- max - 如果给出此可选参数
max
,则只会替换第一个计数事件。
返回值
- 此方法返回一个字符串的副本,其中将所有出现的
old
字符串替换为new
字符串。 如果给出了可选参数max
,则只会替换第一个计数事件。
示例
以下示例显示了replace()
方法的用法 -
#!/usr/bin/python3
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