How do you remove all whitespace characters from a string in Python? | A1Lab@MZeeshanM to PythonEnglish • 8 days ago

How do you remove all whitespace characters from a string in Python?

message-square
0

Use "".join(text.split()) to remove all whitespace characters—including spaces, tabs (\t), newlines (\n), and carriage returns (\r)—from anywhere in a Python string. Because Python strings are immutable, this returns a new string without modifying the original.

Basic Example

# 1. Define a string containing spaces, tabs, and newlines
raw_text = "  Python \t 3.12 \n  Programming  "

# 2. Split on all whitespace and join the parts back together with no separator
clean_text = "".join(raw_text.split())

print(clean_text)  # Output: "Python3.12Programming"

Key Details & Alternative Methods

  • How "".join(text.split()) works: Calling .split() with no arguments splits on every contiguous sequence of Unicode whitespace (�, \t, \n, \r, \v, \f) and discards the whitespace automatically.
  • Regular expressions (re.sub): You can achieve the exact same result using the re module with the \s+ pattern, though "".join(text.split()) is faster in pure Python and requires no imports:
    import re
    
    clean_text = re.sub(r"\s+", "", raw_text)
    
  • Removing ONLY spaces (.replace): If you want to delete literal space characters (" ") while preserving tabs and newlines, use .replace():
    no_spaces = raw_text.replace(" ", "")
    
  • Removing leading/trailing whitespace only (.strip): If you want to keep single spaces between words and only trim the outer edges, use raw_text.strip().

Comparison of Whitespace Removal Methods

Method Removes Spaces (" ") Removes \t, \n, \r Removes Internal Whitespace
"".join(s.split()) Yes Yes Yes
re.sub(r"\s+", "", s) Yes Yes Yes
s.replace(" ", "") Yes No Yes (spaces only)
s.strip() Edges only Edges only No