replace()
方法用另一个字符串替换子字符串的每个匹配项。
示例
text = 'bat ball'
# replace 'ba' with 'ro'
replaced_text = text.replace('ba', 'ro')
print(replaced_text)
# Output: rot roll
replace() 语法
其语法为
str.replace(old, new [, count])
replace() 参数
replace()
方法最多可接受三个参数
- old - 我们要替换的旧子字符串
- new - 将替换旧子字符串的新子字符串
- count(可选)- 您要用新字符串替换旧子字符串的次数
注意:如果未指定count,则 replace()
方法将所有旧子字符串的出现替换为新字符串。
replace() 返回值
replace()
方法返回字符串的副本,其中旧子字符串被新字符串替换。原始字符串保持不变。
如果未找到旧子字符串,则返回原始字符串的副本。
示例 1:使用 replace()
song = 'cold, cold heart'
# replacing 'cold' with 'hurt'
print(song.replace('cold', 'hurt'))
song = 'Let it be, let it be, let it be, let it be'
# replacing only two occurrences of 'let'
print(song.replace('let', "don't let", 2))
输出
hurt, hurt heart Let it be, don't let it be, don't let it be, let it be
更多字符串 replace() 示例
song = 'cold, cold heart'
replaced_song = song.replace('o', 'e')
# The original string is unchanged
print('Original string:', song)
print('Replaced string:', replaced_song)
song = 'let it be, let it be, let it be'
# maximum of 0 substring is replaced
# returns copy of the original string
print(song.replace('let', 'so', 0))
输出
Original string: cold, cold heart Replaced string: celd, celd heart let it be, let it be, let it be
另请阅读