def replaceChar(myString, oldChar, newChar):
# if myString has no characters left, return newString
if myString == '':
return newString
elif myString[0] == oldChar:
# then add newChar to newString
else:
# then add myString[0] to newString
# Chop the first character off of myString
myString = myString[1:]
# recurse
replaceChar(myString, oldChar, newChar)
由于字符串是不可变的,我不能将newChar或oldChar添加到newString。我不能将newString作为一个列表,因为它会被每个递归循环覆盖。我也无法在函数之外定义该列表,因为规则声明一切都必须在函数内部。如何将这些字符添加到我的新字符串中?
答案 0 :(得分:1)
显然,对于这类问题,你实际上永远不会使用这样的递归解决方案,但无论如何它仍然存在:
def replaceChar(inval, old, new):
if inval == '':
return ''
if inval[0] == old:
return new + replaceChar(inval[1:], old, new)
return inval[0] + replaceChar(inval[1:], old, new)
和
print(replaceChar('Do you have some sample input', 'o', 'X'))
产量
DX yXu have sXme sample input