例如:
替换"bananas"一词:
txt = "I like bananas"
x = txt.replace("bananas", "apples")
print(x)
1、定义和用法
replace()
方法将一个指定的字符串替换为另一个指定的字符串。
注意:如果未指定count参数,则将替换所有出现的指定字符串。
2、调用语法
string.replace(oldvalue, newvalue, count)
3、参数说明
参数 | 描述 |
oldvalue | 必需的参数,要被替换的字符串 |
newvalue | 必需的参数,将旧字符串要替换成的字符串 |
count | 可选的。一个数字,指定想要执行替换的次数, 不指定默认替换所有出现的字符串 |
4、使用示例
例如:
替换所有出现的单词“one”:
txt = "one one was a race horse, two two was one too."
x = txt.replace("one", "three")
print(x)
例如:
替换单词“ one”的两个第一次出现:
txt = "one one was a race horse, two two was one too."
x = txt.replace("one", "three", 2)
print(x)