user5619350
user5619350

Reputation:

Recursively replace characters in string using Python

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?

Upvotes: 1

Views: 14203

Answers (1)

sberry
sberry

Reputation: 132018

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

Upvotes: 1

Related Questions