1
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)

Since strings are immutable, I can't add newChar or oldChar to newString. I can't make newString a list, because it will get overwritten with each recursive loop. I also can't define that list outside of the function because the rules state that everything must be inside the function. How can I add these characters to my new string?

2
  • Do you have some sample input / expected output for this? Commented Aug 2, 2016 at 22:32
  • Sure. replaceChar('Do you have some sample input', 'o', 'X') would return 'DX yXu have sXme sample input' Commented Aug 2, 2016 at 22:33

1 Answer 1

1

Obviously you would never actually use a recursive solution like this for this type of problem, but here it is anyway:

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)

And

print(replaceChar('Do you have some sample input', 'o', 'X'))

yields

DX yXu have sXme sample input
Sign up to request clarification or add additional context in comments.

3 Comments

Why do we return the empty string?
I know why. It's because when we returned (new or inval[0] ) + replaceChar(inval[1:] ...) we declared that we were concatenating something with new or inval[0]. We must provide a value, and specifically a string value so that concatenation is possible. That's why we can't just return, or pass, etc. We return "" in order to concatenate a string type with no value.
@manbearpig1 The best lesson I learned a long time ago with recursion is the first step is determining your end case. And yes, you want to always return strings.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.