How to Remove All Whitespace From a Python String?
There are several ways to remove all whitespace from a Python string:
- Using replace() method - It replaces all occurrences of whitespace characters with no space character.
string_with_whitespace = " This is a string with whitespace. "
string_with_no_whitespace = string_with_whitespace.replace(" ", "")
print(string_with_no_whitespace) # "Thisisastringwithwhitespace."
- Using join() method with split() method - The split() method splits the string into a list of words by whitespace characters. The join() method concatenates all the words from the list with no space character.
string_with_whitespace = " This is a string with whitespace. "
string_with_no_whitespace = "".join(string_with_whitespace.split())
print(string_with_no_whitespace) # "Thisisastringwithwhitespace."
- Using regex - Regex is a powerful tool for pattern matching. We can use the sub() function from the re module to replace all whitespace characters with no space character.
import re
string_with_whitespace = " This is a string with whitespace. "
string_with_no_whitespace = re.sub(r"\s+", "", string_with_whitespace)
print(string_with_no_whitespace) # "Thisisastringwithwhitespace."
All three methods produce the same result, a string with no whitespace.