Editor

Python Program to Remove Spaces from a String

Beginner · Strings

This program removes every space from a string, so " Python is fun " becomes "Pythonisfun". The alternatives cover the related jobs: removing tabs and new lines too, trimming only the ends, and squeezing extra spaces down to one.

Program

remove_spaces.py
text = " Python is fun " # or: text = input("Enter a string: ")
result = ""
for ch in text:
if ch != " ":
result += ch
print(f'Original: "{text}"')
print(f'Without spaces: "{result}"')
print("Spaces removed:", len(text) - len(result))
Output
Original:       "  Python   is   fun  "
Without spaces: "Pythonisfun"
Spaces removed: 10

How it works

  1. The loop copies every character except the space " " into result.
  2. The output wraps the strings in quotes so you can see where the spaces were.
  3. Tabs and new lines are not the space character, so this loop keeps them; the first alternative removes them too.
  4. The difference in length between the two strings is the number of spaces removed.

Other ways to write it

Using replace() and split()

Using replace() and split()
text = "Python\tis\nfun to learn"
print("replace():", repr(text.replace(" ", ""))) # spaces only
print("split(): ", repr("".join(text.split()))) # spaces, tabs and new lines
Output
replace(): 'Python\tis\nfuntolearn'
split():   'Pythonisfuntolearn'

replace(" ", "") deletes only the space character, while "".join(text.split()) removes every kind of whitespace. repr() shows a tab as \t and a new line as \n so you can see them.

Trim the ends or squeeze extra spaces

Trim the ends or squeeze extra spaces
text = " Python is fun "
squeezed = " ".join(text.split())
print(f'strip(): "{text.strip()}"')
print(f'lstrip(): "{text.lstrip()}"')
print(f'rstrip(): "{text.rstrip()}"')
print(f'squeezed: "{squeezed}"')
Output
strip():  "Python   is   fun"
lstrip(): "Python   is   fun   "
rstrip(): "   Python   is   fun"
squeezed: "Python is fun"

strip() removes spaces from both ends, lstrip() from the left and rstrip() from the right. Splitting and joining with one space keeps the words but squeezes every gap down to a single space.

Try it yourself

Change the loop so it also skips tabs, by testing ch not in " \t" instead.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises