2016-03-06 80 views
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) 

回答

0

你搞亂了什麼。只需使用:

lst[lst.index(old_element)]=new_element 

如果你想它來代替所有出現的old_element與循環做到這一點:

while old_element in lst: 
    lst[lst.index(old_element)]=new_element 

而對字符串只需使用:

string.replace(old_element,new_element)