How to Remove All Whitespace From a Python String?

python

There are several ways to remove all whitespace from a Python string:

  1. 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."
  1. 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."
  1. 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.

Latest Questions

python How to Fix ""zsh: command not found: python" Error on MacOS X? python How to Fix "xlrd.biffh.XLRDError: Excel xlsx file; not supported" Error in Pandas? python How to Remove All Whitespace From a Python String?