Remove Spaces Recursively

Remove all spaces from string recursively.

AdvancedPhase 3 - Level 4: String-based RecursionExample 4 of 10
remove-spaces-recursively.py
1def remove_spaces(s):
2 # Base case
3 if len(s) == 0:
4 return ""
5
6 # Check first character
7 if s[0] == ' ':
8 return remove_spaces(s[1:])
9 else:
10 return s[0] + remove_spaces(s[1:])
11
12# Test
13text = input("Enter a string: ")
14result = remove_spaces(text)
15print(f"Without spaces: {result}")

Output

Enter a string: Hello World
Without spaces: HelloWorld

What's going on

Skip space, include other characters.

Key Concepts:

Base case: empty string
If space, skip and recurse
Otherwise, include and recurse