Python 字符串 replace() 方法

实例

替换单词 "bananas":

  1. txt = "I like bananas"
  2. x = txt.replace("bananas", "apples")
  3. print(x)

定义和用法

replace() 方法用另一个指定的短语替换一个指定的短语。

注释:如果未指定其他内容,则将替换所有出现的指定短语。


语法

  1. string.replace(oldvalue, newvalue, count)
参数值
参数描述
oldvalue必需。要检索的字符串。
newvalue必需。替换旧值的字符串。
count可选。数字,指定要替换的旧值出现次数。默认为所有的出现。

更多实例

替换所有出现的单词 "one":

  1. txt = "one one was a race horse, two two was one too."
  2. x = txt.replace("one", "three")
  3. print(x)

替换前两次出现的单词 "one":

  1. txt = "one one was a race horse, two two was one too."
  2. x = txt.replace("one", "three", 2)
  3. print(x)

分类导航