Python | Remove spaces from a string
Given a string, write a Python program to remove all spaces from it.
Examples:
Input : g e e k Output : geek Input : Hello World Output : HelloWorld
There are various approaches to remove whitespaces in a string. The first one is the Naive approach, which has been discussed in this article. But here we will discuss all the approaches which are specific to Python.
Approach#1 : Using replace()
Using replace() function, we replace all whitespace with no space(“”).
# Python3 code to remove whitespace def remove(string): return string.replace(" ", "") # Driver Program string = ' g e e k 'print(remove(string)) |
geek
Approach #2 : Using split() and join()
First we use split() function to return a list of the words in the string, using sep as the delimiter string. Then, we use join() to concatenate the iterable.
# Python3 code to remove whitespace def remove(string): return "".join(string.split()) # Driver Program string = ' g e e k 'print(remove(string)) |
geek
Approach #3 : Using Python regex
# Python3 code to remove whitespace import re def remove(string): pattern = re.compile(r'\s+') return re.sub(pattern, '', string) # Driver Program string = ' g e e k 'print(remove(string)) |
geek
Approach #4 : Using translate()
# Python code to remove whitespace import string def remove(string): return string.translate(None, ' \n\t\r') # Driver Program string = ' g e e k 'print(remove(string)) |
geek
Recommended Posts:
- Python | Remove unwanted spaces from string
- Python | Remove additional spaces in list
- Python | Remove spaces from dictionary keys
- Python | Check for spaces in string
- Python | String Split including spaces
- Python code to move spaces to front of string in single traversal
- Python | Remove the given substring from end of string
- Remove all duplicates from a given string in Python
- Ways to remove i'th character from string in Python
- Python | Ways to remove numeric digits from given string
- Python | Ways to remove n characters from start of given string
- Color Spaces in OpenCV | Python
- Python | Visualizing image in different color spaces
- Regex in Python to put spaces between words starting with capital letters
- Python list remove()
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



