Logic Building
def replace_char(s, old, new, index=0):
# Base case
if index >= len(s):
return ""
# Check current character
if s[index] == old:
char = new
else:
char = s[index]
# Recurse
return char + replace_char(s, old, new, index + 1)
# Test
text = input("Enter a string: ")
old_char = input("Enter character to replace: ")
new_char = input("Enter new character: ")
result = replace_char(text, old_char, new_char)
print(f"Result: {result}")Output
Enter a string: Hello Enter character to replace: l Enter new character: x Result: Hexlo
Replace character if matches, otherwise keep.
Key Concepts:
- Base case: index >= len(s)
- Check if current char matches
- Replace or keep, then recurse