How to Remove Whitespace in Python

Whitespace, as the name suggests, is a space in programming language, often used to format the code to increase readability for humans. However, sometimes getting rid of them, especially in data strings becomes pivotal, to ensure the correct reading of actual data. So, let’s dive in and see the various ways of removing whitespaces in Python.

Using strip() Method

The strip() method in Python removes the whitespace from both ends (not from the middle). Here is a simple example:

Output:

Hello World!

Using replace() Method

When we need to remove all the whitespace from the string, not just from the ends, we can use replace(). Here is an example:

Output:

HelloWorld!

Using split() and join() Method

Another clever method to remove all whitespace from a string is to use split() and join() methods together. This way, we first break down the string into words using the split() method, and then join them back together without spaces:

Output:

HelloWorld!

Using re Module

Python’s re module can be used to remove whitespace from a string. This approach employs regular expressions. The ‘\s’ character class matches any whitespace, and the * denotes zero or more occurrences:

Output:

HelloWorld!

Full Example

Conclusion

Apart from improving code readability, removing whitespace becomes particularly important while dealing with data. Python offers several ways to remove whitespace — both from between characters and from the ends of strings.

So, be it utilizing strip(), replace(), a combination of split() and join(), or regex, you can choose any method based on your requirement or convenience.