Remove Occurrences Recursively
Delete every occurrence of one character with recursion. Students compare the first character, skip matches, and rebuild the remaining text in original order.
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
In this one
- Skip exact matches
- Keep nonmatching characters
- Reduce by slicing
How it works
- 1
Return empty text when s is empty.
- 2
Omit the first character if it equals the removal target.
- 3
Otherwise keep it before the processed suffix.
Edge cases
What happens if the target is absent?
What happens if the target is absent?
All original characters are kept.
What if every character matches?
What if every character matches?
The result is empty.
What's going on
remove_char works on the first character and recurses on s[1:]. A matching character contributes nothing; a nonmatch is kept before the processed suffix.
An empty string is the stopping result. Removing a from banana yields bnn. Matching is exact and case-sensitive, and a multi-character removal target does not match a single-character comparison. The slices and pending calls make this a teaching approach.
What happens if the target is absent? All original characters are kept.
What if every character matches? The result is empty.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Which operation removes a matched character?
Pick an answer to check it.
Question 2
What happens if the target is absent?
Pick an answer to check it.
Questions people ask
What happens if the target is absent?
All original characters are kept.
What if every character matches?
The result is empty.
Which operation removes a matched character?
Returning only the processed suffix.
๐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