【发布时间】:2016-03-06 07:54:07
【问题描述】:
我有这段代码可以用另一个子字符串替换一个字符串的现有子字符串。我想修改它,以便它可以用于列表,但我不知道该怎么做。换句话说,我想修改它,以便它可以用新元素替换列表中的现有元素。我想递归地做。
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)
【问题讨论】:
标签: list python-3.x recursion elements