replace()方法把字符串中的 old(舊字符串) 替換成 new(新字符串),如果指定第三個參數count,則替換不超過 count次。
replace()的語法為:
str.replace(old, new [, count])
replace()方法最多可以使用3個參數:
old -您要替換的舊子字符串
new -新的子字符串將替換舊的子字符串
count(可選)-您要用old子字符串替換子new字符串的次數
如果count 未指定,則replace()方法將所有出現的 old子字符串替換為new子字符串。
replace()方法返回字符串的副本,其中old子字符串被new子字符串替換。原始字符串不變。
如果未找到old子字符串,則返回原始字符串的副本。
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
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