Replace Character Recursively
Replace matching characters through a recursive text scan. Students carry old and new values, advance an index, and rebuild a string without changing the source.
1def replace_char(s, old, new, index=0):2 # Base case3 if index >= len(s):4 return ""56 # Check current character7 if s[index] == old:8 char = new9 else:10 char = s[index]1112 # Recurse13 return char + replace_char(s, old, new, index + 1)1415# Test16text = 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: Hexxo
In this one
- Choose a replacement per position
- Carry unchanged search arguments
- Rebuild immutable text
How it works
- 1
Return empty text at the terminal index.
- 2
Select new or the original indexed character.
- 3
Join it with the recursive result for index + 1.
Edge cases
Does old = ab match a source substring?
Does old = ab match a source substring?
No. The code compares one character at a time.
Can new contain several characters?
Can new contain several characters?
Yes. Each matching source character is replaced by that whole string.
What's going on
At each index, the function chooses either new or the original character. It joins that choice to the recursively processed remainder.
The length check returns an empty tail at the end. Matching is case-sensitive. Since each comparison uses one source character, a multi-character old value cannot match; a multi-character replacement can expand the output. Pending concatenations use the call stack.
Does old = ab match a source substring? No. The code compares one character at a time.
Can new contain several characters? Yes. Each matching source character is replaced by that whole string.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What is returned at the end index?
Pick an answer to check it.
Question 2
Does old = ab match a source substring?
Pick an answer to check it.
Questions people ask
Does old = ab match a source substring?
No. The code compares one character at a time.
Can new contain several characters?
Yes. Each matching source character is replaced by that whole string.
What is returned at the end index?
An empty string.
๐Related Content
- ๐
Phase 3 - Learn Concepts
Review Phase 3 concepts and explanations
- ๐
Phase 3 - Quiz
Test your Phase 3 understanding with quiz questions
- ๐ป
Phase 3 - All Practice Problems
Explore all practice problems for Phase 3
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum