How to Remove Spaces From a String in Python?

How to Remove Spaces From a String in Python?

Whitespace removal is a common concept when dealing with strings, and like other languages, Python provides several methods to remove whitespace. In this article, we will explore different techniques to remove white spaces from strings in Python. Let’s delve into the details of each method.

Here are Some methods which we can use for removing white space.

  1. replace()
  2. split() and join()
  3. translate()

Sign up and avail $100 free credits now!!

  1. lstrip() function
  2. rstrip() function
  3. isspace() method

Register and get Auto Scalable instances with a Pay-As-You-Go Pricing Model!

  1. Using Regex and itertools
  2. Using map() and lambda() function
  3. Using NumPy

Let us check all these methods with example

1. replace()

The main purpose of the replace() function is to perform any character or string replacement. However, it can also serve as an efficient way to eliminate white spaces from a given string. By indicating the space character as the initial parameter and utilizing an empty string as the secondary parameter, the process of removing white spaces, or white space removal, can be accomplished.

Input:
str = "W hi te  space"
newStr = str.replace(" ", "")
print(newStr)

Output

Whitespace

2. split() and join()

The collaborative usage of the split() and join() methods is yet another approach for eliminating white spaces. This technique involves breaking down the string into individual words using spaces as separators and subsequently merging them back together, devoid of any spaces. However, it’s worth noting that this approach might not yield the desired outcome when dealing with sentences.

Note:- work proper with single word with whitespace
Input:.
str = "W hi te  space"
newStr = "".join(str.split())
print(newStr)

Output

Whitespace

Note:- Not work for sentence as expected
Input:
str = "W hi te  space need to remove"
newStr = "".join(str.split())
print(newStr)

Output

Whitespaceneedtoremove

Sign up and avail $100 free credits now!!

3. translate()

The translate() method can be employed by creating a translation table to remove specific characters. In this case, we replace the ASCII value of the space character (32) with an empty string.

Input:
str = "W hi te  space"
newStr =  str.translate({32: ""})
print(newStr)

Output

Whitespace

4. lstrip()

The lstrip() method allows us to remove characters, including white spaces, from the left side of a string. We can achieve whitespace removal from the left side by specifying a character sequence to be removed.

Input:
string = "   This string need to remove whitespace from left side"
string_new = string.lstrip("Th")
print(string_new)

Output

This string need to remove whitespace from left side.

To remove spaces from a string in Python, use ‘replace()’ to directly replace spaces with an empty string or combine ‘join()’ and ‘split()’ to rebuild the string without spaces. Experience fast and reliable Python hosting at AccuWeb.Cloud, and start your free trial today!

5. rstrip()

Similar to lstrip(), the rstrip() method removes characters from the right side of a string. We can remove white spaces following that sequence by specifying a character sequence.

Input:
string = "This string need to remove whitespace from right side   "
string_new = string.lstrip("de")
print(string_new)

Output

This string need to remove whitespace from right side

Check for our Python Hosting with optimized Python stack & pre-configured caching mechanisms!

6. isspace()

The isspace() method checks for the existence of white spaces within a string. We can obtain a string without white spaces by manually removing these spaces using a loop. Once we’ve confirmed the presence of white spaces, we can proceed to eliminate these spaces in various manners. Here we are doing this via loop.

Input:
str = ' This s tring needs to remove whitespace ' 
a="" 
for i in str: 
  if(not i.isspace()): 
    a+=i 
print(a)

Output

Thisstringneedstoremovewhitespace

7. Regex and itertools

Regular expressions (regex) can help identify whitespace occurrences in a string. By using the “re” library to replace all whitespace matches with an empty string, and then filtering out spaces using itertools, we achieve whitespace removal.

Input:
import re
import itertools
str = " This String Ne eds to remo ve white space   "
regx = re.compile(r's+')
str = re.sub(regx, '', str)
resList = list(itertools.filterfalse(lambda x: x == ' ', str))
finalStr = ''.join(resList)
print(finalStr)

Output

ThisStringNeedstoremovewhitespace

8. map() and lambda() function

The map() function along with a lambda function can be utilized to strip spaces from each word in a string. Converting the resulting map object into a list and then joining the list elements provides the desired string.

Input:
str = ' This Str ing i gonna tes t with map and lanbda '
str = ''.join(list(map(lambda x: x.strip(), str.split())))
print(str)

Output

ThisStringigonnatestwithmapandlanbda

Register and get Auto Scalable instances with a Pay-As-You-Go Pricing Model!

9. NumPy

By leveraging the NumPy library, we can split a string into individual characters and then replace spaces.

Input:
import numpy as np
string = '  Te st String '
finalStr = np.char.replace(string, ' ', '')
print(finalStr)

Output

TestString

Conclusion

In conclusion, Python offers a variety of methods to remove white spaces from strings, each with its advantages and use cases. Depending on the specific requirements of your project, you can choose the method that best suits your needs.

Save $100 in the next
5:00 minutes?

Register Here