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
Original: " Python is fun " Without spaces: "Pythonisfun" Spaces removed: 10
How it works
- The loop copies every character except the space
" "intoresult. - The output wraps the strings in quotes so you can see where the spaces were.
- Tabs and new lines are not the space character, so this loop keeps them; the first alternative removes them too.
- The difference in length between the two strings is the number of spaces removed.
Other ways to write it
Using replace() and split()
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
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.
Related programs
- Remove Punctuation from a String
- Replace a Character in a String
- Count Letters, Digits and Spaces in a String
- Count Vowels, Consonants, Uppercase and Lowercase Letters
- Check a Palindrome String
- Reverse a String
- Generate a Random Password
- Count the Frequency of Each Character in a String
- Count the Words in a String
All Python programs · CBSE class 12 practical file · Python exercises