Python 字符串 replace() 方法
replace()
方法将字符串中每个匹配的子串替换为另一个字符串。
示例
text = 'bat ball'
# 将 'ba' 替换为 'ro'
replaced_text = text.replace('ba', 'ro')
print(replaced_text)
# 输出: rot roll
replace() 语法
它的语法是:
str.replace(old, new [, count])
replace() 参数
replace()
方法最多可以接受三个参数:
- old - 我们想要替换的旧子串
- new - 将替换旧子串的新子串
- count(可选)- 你想要替换旧子串为新字符串的次数
注意:如果没有指定 count,replace()
方法会替换所有出现的旧子串为新字符串。
replace() 返回值
replace()
方法返回一个字符串的副本,其中旧子串被新字符串替换。原始字符串保持不变。
如果没有找到旧子串,它会返回原始字符串的副本。
示例 1:使用 replace()
song = 'cold, cold heart'
# 将 'cold' 替换为 'hurt'
print(song.replace('cold', 'hurt'))
song = 'Let it be, let it be, let it be, let it be'
# 只替换两次 '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
更多关于 String replace() 的示例
song = 'cold, cold heart'
replaced_song = song.replace('o', 'e')
# 原始字符串保持不变
print('原始字符串:', song)
print('替换后的字符串:', replaced_song)
song = 'let it be, let it be, let it be'
# 最多替换 0 个子串
# 返回原始字符串的副本
print(song.replace('let', 'so', 0))
输出
原始字符串: cold, cold heart
替换后的字符串: celd, celd heart
let it be, let it be, let it be