Replace Character Recursively

Replace all occurrences of a character recursively.

AdvancedPhase 3 - Level 4: String-based RecursionExample 5 of 10
replace-character-recursively.py
1def replace_char(s, old, new, index=0):
2 # Base case
3 if index >= len(s):
4 return ""
5
6 # Check current character
7 if s[index] == old:
8 char = new
9 else:
10 char = s[index]
11
12 # Recurse
13 return char + replace_char(s, old, new, index + 1)
14
15# Test
16text = input("Enter a string: ")
17old_char = input("Enter character to replace: ")
18new_char = input("Enter new character: ")
19result = replace_char(text, old_char, new_char)
20print(f"Result: {result}")

Output

Enter a string: Hello
Enter character to replace: l
Enter new character: x
Result: Hexlo

What's going on

Replace character if matches, otherwise keep.

Key Concepts:

Base case: index >= len(s)
Check if current char matches
Replace or keep, then recurse