1
我有這個代碼可以用另一個子字符串替換一個字符串的現有子字符串。我想修改它,以便它可以用於列表,但我不知道如何去做。換句話說,我想修改它,以便它可以用新元素替換列表中的現有元素。我想遞歸地執行它。python遞歸幫助修改列表
def rec_replace(string, a, b):
if not string: #if the string is empty
return ""
elif string[:len(b)] == b: #if the string start with b, replace it with a
return a + rec_replace(string[len(b):], a, b)
else: #else, add this character and go to the next one
return string[0] + rec_replace(string[1:], a, b)