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 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: 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
🔗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