Remove Occurrences Recursively
Remove all occurrences of a character recursively.
AdvancedPhase 3 - Level 4: String-based RecursionExample 6 of 10
remove-occurrences-recursively.py
1def remove_char(s, char_to_remove):2 # Base case3 if len(s) == 0:4 return ""56 # Check first character7 if s[0] == char_to_remove:8 return remove_char(s[1:], char_to_remove)9 else:10 return s[0] + remove_char(s[1:], char_to_remove)1112# Test13text = input("Enter a string: ")14char = input("Enter character to remove: ")15result = remove_char(text, char)16print(f"Result: {result}")
Output
Enter a string: Hello Enter character to remove: l Result: Heo
What's going on
Skip character if matches, include otherwise.
Key Concepts:
Base case: empty string
If matches, skip and recurse
Otherwise, include and 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