
replace()方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数count,则替换不超过 count次。
replace()的语法为:
str.replace(old, new [, count])
replace()参数
replace()方法最多可以使用3个参数:
- old -您要替换的旧子字符串 
- new -新的子字符串将替换旧的子字符串 
- count(可选)-您要用old子字符串替换子new字符串的次数 
如果count 未指定,则replace()方法将所有出现的 old子字符串替换为new子字符串。
replace()返回值
replace()方法返回字符串的副本,其中old子字符串被new子字符串替换。原始字符串不变。
如果未找到old子字符串,则返回原始字符串的副本。
示例1:如何使用replace()?
song = 'cold, cold heart'
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
