Open In App

Python – Ways to remove multiple empty spaces from string List

Last Updated : 21 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 : Using loop + strip() This is a way in which we can perform this task. In this, we strip the strings using strip(), it reduces to a single space, and then it can be tested for a NULL value. Returns True if the string is a single space and hence helps in filtering. 

Python3




# Python3 code to demonstrate working of
# Remove multiple empty spaces from string List
# Using loop + strip()
 
# initializing list
test_list = ['gfg', ' ', ' ', 'is', '         ', 'best']
 
# printing original list
print("The original list is : " + str(test_list))
 
# Remove multiple empty spaces from string List
# Using loop + strip()
res = []
for ele in test_list:
    if ele.strip():
        res.append(ele)
     
# printing result
print("List after filtering non-empty strings : " + str(res))


Output : 

The original list is : ['gfg', '   ', ' ', 'is', '            ', 'best']
List after filtering non-empty strings : ['gfg', 'is', 'best']

Time Complexity: O(n) where n is the total number of values in the list “test_list”. 
Auxiliary Space: O(n) where n is the total number of values in the list “test_list”.

  Method #2: Using list comprehension + strip() The combination of the above functions can also be used to perform this task. In this, we employ a one-liner approach to perform this task instead of using the loop. 

Python3




# Python3 code to demonstrate working of
# Remove multiple empty spaces from string List
# Using list comprehension + strip()
 
# initializing list
test_list = ['gfg', ' ', ' ', 'is', '         ', 'best']
 
# printing original list
print("The original list is : " + str(test_list))
 
# Remove multiple empty spaces from string List
# Using list comprehension + strip()
res = [ele for ele in test_list if ele.strip()]
     
# printing result
print("List after filtering non-empty strings : " + str(res))


Output : 

The original list is : ['gfg', '   ', ' ', 'is', '            ', 'best']
List after filtering non-empty strings : ['gfg', 'is', 'best']

Time Complexity: O(n)
Auxiliary Space: O(n), where n is length of list.

Method #3 : Using find()

Python3




# Python3 code to demonstrate working of
# Remove multiple empty spaces from string List
# Using find()
 
# initializing list
test_list = ['gfg', ' ', ' ', 'is', '         ', 'best']
 
# printing original list
print("The original list is : " + str(test_list))
 
# Remove multiple empty spaces from string List
# Using find()
res = []
for ele in test_list:
    if ele.find(' ')==-1:
        res.append(ele)
     
# printing result
print("List after filtering non-empty strings : " + str(res))


Output

The original list is : ['gfg', ' ', ' ', 'is', '\t\t ', 'best']
List after filtering non-empty strings : ['gfg', 'is', 'best']

The Time and Space Complexity for all the methods are the same:

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #4: Using lambda function

Python3




# Python3 code to demonstrate working of
# Remove multiple empty spaces from string List
# initializing list
test_list = ['gfg', ' ', ' ', 'is', '         ', 'best']
 
# printing original list
print("The original list is : " + str(test_list))
 
res = list(filter(lambda x: x[0].lower() != x[0].upper(), test_list))
 
# printing result
print("List after filtering non-empty strings : " + str(res))


Output

The original list is : ['gfg', ' ', ' ', 'is', '         ', 'best']
List after filtering non-empty strings : ['gfg', 'is', 'best']

Time complexity: O(n), where n is the length of the test_list. 
Auxiliary Space: O(n), extra space of size n is required

Method #5:  Using itertools.filterfalse()

Python3




# Python3 code to demonstrate working of
# Remove multiple empty spaces from string List
# initializing list
import itertools
 
test_list = ['gfg', ' ', ' ', 'is', '         ', 'best']
 
# printing original list
print("The original list is : " + str(test_list))
 
res = list(itertools.filterfalse(lambda x: x[0].upper() == x[0].lower(), test_list))
 
# printing result
print("List after filtering non-empty strings : " + str(res))


Output

The original list is : ['gfg', ' ', ' ', 'is', '         ', 'best']
List after filtering non-empty strings : ['gfg', 'is', 'best']

Time Complexity: O(n)

Auxiliary Space: O(n)

Approach 6: Using str.isspace()
 

Python3




#Python3 code to demonstrate working of
#Remove multiple empty spaces from string List
#Initializing list
test_list = ['gfg', ' ', ' ', 'is', ' ', 'best']
 
#Printing original list
print("The original list is : " + str(test_list))
 
#Remove multiple empty spaces from string List
res = [ele for ele in test_list if not ele.isspace()]
 
#Printing result
print("List after filtering non-empty strings : " + str(res))


Output

The original list is : ['gfg', ' ', ' ', 'is', ' ', 'best']
List after filtering non-empty strings : ['gfg', 'is', 'best']

Time Complexity: O(n)
Auxiliary Space: O(n)
Explanation:
In this approach, we use the str.isspace() method which returns True if all the characters in the string are whitespaces and False otherwise.
We loop through the list and use the str.isspace() method to check if the string only consists of whitespaces or not.
If not, then we append the string to the result list. Finally, we return the result list which contains all the non-empty strings from the original list.

Approach #7:Using regex.findall() method

Python3




import re
#Python3 code to demonstrate working of
#Remove multiple empty spaces from string List
#Initializing list
test_list = ['gfg', ' ', ' ', 'is', ' ', 'best']
 
#Printing original list
print("The original list is : " + str(test_list))
 
string = ''.join(test_list)
#Remove multiple empty spaces from string List
res = re.findall(r'[a-zA-Z]+', string)
 
#Printing result
print("List after filtering non-empty strings : " + str(res))


Output

The original list is : ['gfg', ' ', ' ', 'is', ' ', 'best']
List after filtering non-empty strings : ['gfg', 'is', 'best']

Time Complexity: O(n)
Auxiliary Space: O(n)



Next Article

Similar Reads

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
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 | Remove spaces from a string
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 t
5 min read
Python - Remove empty List from List
Sometimes, while working with python, we can have a problem in which we need to filter out certain empty data. These can be none, empty string, etc. This can have applications in many domains. Let us discuss certain ways in which the removal of empty lists can be performed. Method 1: Using list comprehension: This is one of the ways in which this p
8 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 empty tuples from a list
In this article, we will see how can we remove an empty tuple from a given list of tuples. We will find various ways, in which we can perform this task of removing tuples using various methods and ways in Python. Examples: Input : tuples = [(), ('ram','15','8'), (), ('laxman', 'sita'), ('krishna', 'akbar', '45'), ('',''),()]Output : [('ram', '15',
8 min read
Python | Remove and print every third from list until it becomes empty
Given a list of numbers, Your task is to remove and print every third number from a list of numbers until the list becomes empty. Examples: Input : [10, 20, 30, 40, 50, 60, 70, 80, 90] Output : 30 60 90 40 80 50 20 70 10 Explanation: The first third element encountered is 30, after 30 we start the count from 40 for the next third element which is 6
4 min read
Python | Remove empty strings from list of strings
In many scenarios, we encounter the issue of getting an empty string in a huge amount of data and handling that sometimes becomes a tedious task. Let's discuss certain way-outs to remove empty strings from list of strings. Method #1: Using remove() This particular method is quite naive and not recommended use, but is indeed a method to perform this
7 min read
Python | Remove trailing empty elements from given list
Given a list, the task is to remove trailing None values from last of the list. Let's discuss a few methods to solve the given task. Examples: Input: [1, 2, 3, 4, None, 76, None, None] Output: [1, 2, 3, 4, None, 76] Input: [1, 2, None, None, None, None, None, 5] Output: [1, 2, None, None, None, None, None, 5] Method #1: Using naive method C/C++ Cod
7 min read
Python - Remove empty value types in dictionaries list
Sometimes, while working with Python dictionaries, we require to remove all the values that are virtually Null, i.e does not hold any meaningful value and are to be removed before processing data, this can be an empty string, empty list, dictionary, or even 0. This has applications in data preprocessing. Let us discuss certain ways in which this ta
7 min read
three90RightbarBannerImg