轻松上手,快乐学习!

Python 字符串 replace() 方法


实例

替换“bananas”这个词:

txt "I like bananas"

x = txt.replace("bananas", "apples")

print(x)

运行示例»

定义和用法

replace()方法将指定的短语替换为另一个指定的短语。
注意: 如果未指定任何其他内容,则将替换所有出现的指定短语。

语法

string.replace(oldvalue, newvalue, count)

参数值

Parameter Description
oldvalue 必须项。检索的字符串。
newvalue 必须项。替换检索到的字符串。
count 可选项。替换检索到的次数。默认替换所有

更多例子

实例

替换所有出现的单词“one”:

txt = "one one was a race horse, two two was one too."

x = txt.replace("one", "three")

print(x)

运行示例»

实例

替换前2次出现的单词“one”:

txt = "one one was a race horse, two two was one too."

x = txt.replace("one", "three", 2)

print(x)

运行示例»