Open In App
Related Articles

Python | Remove spaces from a string

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Removing spaces from a string involves eliminating any whitespace characters within the string. This can be accomplished using various methods in Python like replace(), translate(), istrip(), etc.

By removing spaces from a string, you can manipulate and process the string more easily, perform comparisons, or use it in various other operations. In this article, we will see how to remove whitespace from string Python.

Input: g e e k
Output: geek
Input: Hello   World
Output: HelloWorld
Explanation: In This, we are removing whitespaces from a string Python.

How to Remove Spaces from a String in Python

There are various approaches to removing 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 that are specific to removing whitespace from string Python.

  • Using replace() 
  • Using translate() 
  • Using lstrip() function
  • Using rstrip() function
  • Using isspace() method
  • Using Regex and itertools
  • Using split() and strip() function
  • Using NumPy

1. Remove Whitespace from String using Replace()

In this example, we will remove whitespace from the string using replace(). We have taken a string and we have replaced all whitespaces with empty string.

Python3

# Python3 code to remove whitespace
def remove(string):
    return string.replace(" ", "")
 
 
# Driver Program
string = ' g e e k '
print(remove(string))

                    

Output

geek

2. Remove Whitespace from String using Translate() 

In this example, we will remove whitespace from the string using translate(). translate() returns a string that is a modified string of givens string according to given translation mappings.

Python3

# 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))

                    

Output

geek

3. Remove Whitespace from String using lstrip() function

We will remove whitespace from the string using lstrip() in this example. The lstrip() creates a new string by either deleting whitespace from the string’s “left” side or its leading whitespace.

Python3

string = "www.geeksforgeeks.org www."
 
string_new = string.lstrip("w.")
 
print(string_new)

                    

Output

geeksforgeeks.org www.


4. Delete Whitespace from String using rstrip() function

We will remove whitespace from the string using rstrip() in this example. The rstrip() creates a new string by removing the trailing whitespace. Eliminating the white spaces from the string’s “right” side makes it simpler to recall.

Python3

string = "www.geeksforgeeks.org www."
 
string_new = string.rstrip("w.")
 
print(string_new)

                    

Output

www.geeksforgeeks.org 


5. Trim Extra Spaces from String using isspace() method

In this example, we will remove whitespace from the string using isspace(). We have taken a string and with a for loop we are traversing through the string and if the space is occurring then we are skipping the concatenation of the string character else we are assigning it.

Python3

# Python3 code to remove whitespace
def remove(string):
    ns=""
    for i in string:
        if(not i.isspace()):
            ns+=i
    return ns   
# Driver Program
string = ' g e e k '
print(remove(string))

                    

Output

geek


6. Remove Whitespace from String using Regex and itertools

In this example, we will remove whitespace from the string using Regex and itertools.filterfalse(). A Regular Expression (RegEx) is a unique string of characters used to find a string or group of strings.

It may compare a text to a pattern to determine whether it is present or absent. It can also divide a pattern into one or more sub-patterns. The function filters out all whitespace characters from the input string using the itertools.filterfalse() method, producing an iterable that only contains non-whitespace characters.

To create the final output string, the process first turns iterable into a list and uses join() to concatenate all of its members.

Python3

# Python code to remove whitespace
import re
import itertools
 
def remove(string):
    pattern = re.compile(r'\s+')
    string = re.sub(pattern, '', string)
    resList = list(itertools.filterfalse(lambda x: x == ' ', string))
    return ''.join(resList)
 
string = " g e e k "
print(remove(string))

                    

Output

geek

7. Remove Whitespace from String using split() function

In this example, we have defined the string variable with whitespace, we have split it into a list of substrings.

We then remove leading and trailing whitespaces from each substring using map() and lambda() function.

Finally we convert the map() object to a list, join the list of substrings into a single string using join(). Assign the resulting string to “string” variable, and print the final “string” variable without whitespaces.

Python3

string = ' g e e k '
 
string = ''.join(list(map(lambda x: x.strip(), string.split())))
 
print(string)

                    

Output

geek


8. Trim Blank Spaces from String using NumPy

In this example, we will remove whitespace from the string Python using Numpy. We have imported NumPy and we have created a remove() and replaced all occurrences of whitespaces in the input string with an empty string and returned a final string.

Python3

import numpy as np
 
def remove(string):
    return np.char.replace(string, ' ', '')
 
# Driver Code
string = ' g e e k '
print(remove(string))

                    

Output

geek

We have covered several ways to remove spaces from a string. We have discussed many simple and detailed steps if you want to remove whitespace from the string in Python.

Read Other Python List Methods

Also Read:



Last Updated : 21 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads