Python 字符串 replace() 方法
Python基础 2022-06-06 15:21:53小码哥的IT人生shichen
Python 字符串 replace() 方法
实例
替换单词 "bananas":
txt = "I like bananas"
x = txt.replace("bananas", "apples")
print(x)
完整实例:
txt = "I like bananas"
x = txt.replace("bananas", "apples")
print(x)
定义和用法
replace() 方法用另一个指定的短语替换一个指定的短语。
注释:如果未指定其他内容,则将替换所有出现的指定短语。
语法
string.replace(oldvalue, newvalue, count)
参数值
参数 | 描述 |
---|---|
oldvalue | 必需。要检索的字符串。 |
newvalue | 必需。替换旧值的字符串。 |
count | 可选。数字,指定要替换的旧值出现次数。默认为所有的出现。 |
更多实例
示例代码:
替换所有出现的单词 "one":
txt = "one one was a race horse, two two was one too."
x = txt.replace("one", "three")
print(x)
完整实例:
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)
完整实例:
txt = "one one was a race horse, two two was one too."
x = txt.replace("one", "three", 2)
print(x)