Python string recursion
Question: I have to recursively replace characters in a string with new characters. I'm
a bit stuck right now, however. I cannot import anything, so here is my code:

EDIT: I forgot to mention that I'm not allowed to use any built in functions
besides len() and index/splice operators. This means I can't use 'in'. This is
a homework question, but I don't expect you guys to solve it for me, just to
point out why my code isn't working. Thanks!

    
    
    def replace_char(astr, old_char, new_char):
        newstr = ""
        if astr == "":
            return newstr
        elif astr[0] == old_char:
            newstr += new_char
            return replace_char(astr[1:], old_char, new_char)
        else:
            newstr += astr[0]
            return replace_char(astr[1:], old_char, new_char)
    

Any ideas on why it isn't working? Thanks!


Answer: Here's what you're looking for:

    
    
    def replace_char(astr, old_char, new_char):
        if astr == "":
            return astr
        elif astr[0] == old_char:
            return new_char + replace_char(astr[1:], old_char, new_char)
        else:
            return astr[0] + replace_char(astr[1:], old_char, new_char)
    

The only string you ever returned in your old code was an empty one:

    
    
    newstr = ""
        if astr == "":
            return newstr
    

You need to be adding characters to your return value as you recurse through
the string.

