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:
1 2 3 |
string = " Hello World! " result = string.strip() print(result) |
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:
1 2 3 |
string = " Hello World! " result = string.replace(" ", "") print(result) |
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:
1 2 3 |
string = " Hello World! " result = ''.join(string.split()) print(result) |
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:
1 2 3 4 |
import re string = " Hello World! " result = re.sub('\s', '', string) print(result) |
Output:
HelloWorld!
Full Example
1 2 3 4 |
string = " Hello World! " print(string.strip()) print(string.replace(" ", "")) print(''.join(string.split())) |
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.