Remove Spaces Recursively

Remove all spaces from string recursively.

Logic BuildingAdvanced
Logic Building
def remove_spaces(s):
    # Base case
    if len(s) == 0:
        return ""
    
    # Check first character
    if s[0] == ' ':
        return remove_spaces(s[1:])
    else:
        return s[0] + remove_spaces(s[1:])

# Test
text = input("Enter a string: ")
result = remove_spaces(text)
print(f"Without spaces: {result}")

Output

Enter a string: Hello World
Without spaces: HelloWorld

Skip space, include other characters.

Key Concepts:

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