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. By removing spaces from a string, you can manipulate and process the string more easily, perform comparisons, or use it in various other operations.
Examples: Write a Python program to remove all spaces from it.
Input : g e e k Output: geek
Input : Hello World Output: HelloWorld
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 which are specific to Python.
Remove spaces from a string using Python replace()
In this example, 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)) |
geek
Remove Whitespaces From String using Python split() and Python join()
First, we use the split() function to return a list of the words in the string, using sep as the delimiter Python string. Then, we use join() to concatenate the iterable.
Python3
# Python3 code to remove whitespace def remove(string): return "".join(string.split()) # Driver Program string = ' g e e k ' print (remove(string)) |
Output:
geek
Remove spaces from a string using Python Regex
In order to find a string or group of strings, a Regular Expression (RegEx) is a unique string of characters. 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.
Python3
# 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)) |
Output
geek
Remove All Spaces and Newline Characters 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
Remove Whitespaces From String using Reduce function
Reduce function iterate over the string and it joins to the element of the string to result if it is not white space.
Python3
# Python code to remove whitespace #importing module from functools import reduce #Function to remove white space def remove(string): return reduce ( lambda x, y: (x + y) if (y ! = " " ) else x, string, ""); # Driver Program string = ' g e e k ' print (remove(string)) |
Output:
geek
Remove spaces from a string using lstrip() function
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.
Remove spaces from a string using rstrip() function
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
Using isspace() method
In this example, 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
Using itertools.filterfalse() method
The function first 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 method first turns iterable into a list and uses join() to concatenate all of its members.
Python3
# Python code to remove whitespace # importing module import itertools # Function to remove white space def remove(string): resList = list (itertools.filterfalse( lambda x: x = = ' ' , string)) return ''.join(resList) # Driver Program string = " g e e k " print (remove(string)) |
Output
geek
Using regex.findall() method
The remove() method in this Python code uses regular expressions to eliminate any whitespace characters from a specified text. The function first locates all of the alphabetic non-whitespace characters in the input string using the re. find () method, and then it concatenates them using the. join() method. The remove function is called by the driver programme, which first constructs a string variable called string containing whitespace characters before sending the string as input.
Python3
# Python3 code to remove whitespace import re def remove(string): return ' '.join(re.findall(r' [a - zA - Z] + ', string)) # Driver Program string = ' g e e k ' print (remove(string)) |
Output
geek
Using map() and lambda() function
In this example, we have defined the string variable with whitespace, we have split it into a list of substrings, remove leading and trailing whitespaces from each substring using map(), lambda function, 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) #This code is contributed by Vinay Pinjala. |
Output
geek
Using for loop and join()
In this example, 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
string = "Hello World" new_string = "" for char in string: if char ! = " " : new_string + = char string = "".join(new_string) print (string) # Output: HelloWorld |
Output
HelloWorld
Using NumPy
In this example, 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)) #This code is contributed by Rayudu. |
Output:
geek
Please Login to comment...