Remove Spaces Recursively
Remove ordinary spaces recursively from text. Students choose whether to keep the first character and distinguish a literal space from every whitespace character.
1def remove_spaces(s):2 # Base case3 if len(s) == 0:4 return ""56 # Check first character7 if s[0] == ' ':8 return remove_spaces(s[1:])9 else:10 return s[0] + remove_spaces(s[1:])1112# Test13text = input("Enter a string: ")14result = remove_spaces(text)15print(f"Without spaces: {result}")
Output
Enter a string: Hello World Without spaces: HelloWorld
In this one
- Filter through recursive returns
- Match literal spaces
- Preserve kept character order
How it works
- 1
Return empty text at an empty suffix.
- 2
If the first character is a space, skip it.
- 3
Otherwise prepend it to the processed suffix.
Edge cases
Are tabs removed?
Are tabs removed?
No. Only an ordinary space matches the condition.
What if every character is a space?
What if every character is a space?
The final result is empty.
What's going on
An empty string ends recursion. For a leading ordinary space, the function returns only the processed suffix; otherwise it keeps s[0] before that suffix.
For a b, the returned text is ab. Character order is preserved because kept characters are joined before the suffix result. Tabs and other whitespace are not the literal ' ' tested here, so they remain. Calls and slices use memory.
Are tabs removed? No. Only an ordinary space matches the condition.
What if every character is a space? The final result is empty.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Which branch keeps a character?
Pick an answer to check it.
Question 2
Are tabs removed?
Pick an answer to check it.
Questions people ask
Are tabs removed?
No. Only an ordinary space matches the condition.
What if every character is a space?
The final result is empty.
Which branch keeps a character?
The nonspace branch.
๐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