The Wayback Machine - https://web.archive.org/web/20240708024838/https://www.geeksforgeeks.org/python-remove-spaces-from-a-string/
Open In App

Python | Remove spaces from a string

Last Updated : 21 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
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:



Previous Article
Next Article

Similar Reads

Python | Remove unwanted spaces from string
Sometimes, while working with strings, we may have situations in which we might have more than 1 spaces between intermediate words in strings that are mostly unwanted. This type of situation can occur in web development and often needs rectification. Let's discuss certain ways in which this task can be performed. Examples: Example 1: Input: GfG is
4 min read
Python - Ways to remove multiple empty spaces from string List
Sometimes, while working with Python strings, we have a problem in which we need to perform the removal of empty spaces in Strings. The problem of filtering a single space is easier. But sometimes we are unaware of the number of spaces. This has applications in many domains. Let's discuss certain ways in which this task can be performed. Method #1
6 min read
Python | Remove spaces from dictionary keys
In Python, dictionary is a collection which is unordered, changeable and indexed. Dictionaries are written with curly brackets, and they have keys and values. It is used to hash a particular key. Let's see how to remove spaces from dictionary keys in Python. Method #1: Using translate() function here we visit each key one by one and remove space wi
5 min read
Python | Remove additional spaces in list
Sometimes, we have a list that contains strings and spaces in between them. We desire to have uniformity, so that later if we decide them, we just have single spaces between the lists. Hence its sometimes necessary to remove the additional unnecessary spaces between the words in a list. Let's discuss certain ways in which this can be done. Method #
3 min read
Remove spaces from column names in Pandas
Removing spaces from column names in pandas is not very hard we easily remove spaces from column names in pandas using replace() function. We can also replace space with another character. Let's see the example of both one by one. Example 1: remove the space from column name Python Code # import pandas import pandas as pd # create data frame Data =
1 min read
Python code to move spaces to front of string in single traversal
Given a string that has set of words and spaces, write a program to move all spaces to front of string, by traversing the string only once. Examples: Input : str = "geeks for geeks" Output : str = " geeksforgeeks" Input : str = "move these spaces to beginning" Output : str = " movethesespacestobeginning" There were four space characters in input, a
5 min read
Python | String Split including spaces
The problems and at the same time applications of list splitting are quite common while working with python strings. The spaces usually tend to ignore in the use cases. But sometimes, we might not need to omit the spaces but include them in our programming output. Let's discuss certain ways in which this problem can be solved. Method #1: Using spli
4 min read
Python | Check for spaces in string
Sometimes, we might have a problem in which we need to check if the string has any blank spaces. This kind of problem can be in Machine Learning domain to get specific type of data set. Let's discuss certain ways in which this kind of problem can be solved. Method #1 : Using regex This kind of problem can be solved using the regex utility offered b
8 min read
Python | Test if String contains Alphabets and Spaces
Sometimes, while testing of credibility of string being a part of containing just alphabets, an exception of spaces has to be mentioned explicitly and becomes a problem. This can occur in domains that deal with data. Lets discuss certain ways in which this task can be performed. Method #1 : Using all() + isspace() + isalpha() This is one of the way
5 min read
Python - Avoid Spaces in string length
Given a String, compute all the characters, except spaces. Input : test_str = 'geeksforgeeks 33 best' Output : 19 Explanation : Total characters are 19. Input : test_str = 'geeksforgeeks best' Output : 17 Explanation : Total characters are 17 except spaces. Method #1 : Using isspace() + sum() In this, we check for each character to be equal not to
6 min read
Practice Tags :
three90RightbarBannerImg