How to Remove Whitespace from a String in Python

Short answer
Use text.strip() to remove whitespace from both ends, or "".join(text.split()) to remove it everywhere, including spaces, tabs and newlines in the middle.

"Remove whitespace" can mean three different things: trim the edges, collapse repeated spaces into one, or delete every space completely. Python has a tool for each, and picking the right one is the whole trick. Messy whitespace usually comes from user input, copied text, CSV files and lines read from a file, where an invisible trailing newline or space can quietly break comparisons.

Strings are immutable, so none of these methods change the original. They return a new string that you must store or use.

Quick facts
Trim both endstext.strip()
Remove all spacestext.replace(" ", "")
Remove all whitespace"".join(text.split())
Collapse repeated spaces" ".join(text.split())

Remove leading and trailing whitespace with strip()

strip() removes whitespace characters (spaces, tabs, newlines) from the start and end only. Use lstrip() for the left side and rstrip() for the right side.

Python
name = "   Asha Rao \n"
print(repr(name.strip()))
print(repr(name.lstrip()))
print(repr(name.rstrip()))

Printing with repr() makes invisible characters visible, which is handy when debugging.

Remove every space inside a string with replace()

replace() swaps one piece of text for another. Replacing a space with an empty string deletes it. This only targets the plain space character, not tabs or newlines.

Python
phone = "98 765 43210"
print(phone.replace(" ", ""))

Remove all kinds of whitespace with split() and join()

Calling split() with no argument splits on any run of whitespace and drops empty pieces. Joining the pieces with an empty string removes all whitespace; joining with a single space collapses repeats into one space.

Python
messy = "  too   many\tspaces\nhere  "
print("".join(messy.split()))
print(" ".join(messy.split()))

The second form is the usual way to normalise spacing while keeping the words apart.

Use a regular expression for custom whitespace rules

For special cases, such as removing only runs of two or more spaces, the re module is more flexible. re.sub(r"\s+", "", text) removes every whitespace character, and re.sub(r"\s+", " ", text) collapses runs into one space.

Which whitespace removal method fits your task?

GoalCodeInput " a b " gives
Trim both endss.strip()"a b"
Trim left onlys.lstrip()"a b "
Remove plain spacess.replace(" ", "")"ab"
Remove all whitespace"".join(s.split())"ab"
Normalise spacing" ".join(s.split())"a b"

Examples you can run

Press Run, then edit the code and run it again.

Clean user input with strip()

Trimming input before using it avoids surprises such as "yes " == "yes" being False.

Clean user input with strip()
answer = "  yes "
print(answer == "yes")
print(answer.strip() == "yes")
Expected outputFalse
True

Remove all spaces and collapse extra spaces

replace() deletes spaces; split() plus join() normalises them.

Remove all spaces and collapse extra spaces
title = "  python   for   beginners "
print(title.replace(" ", ""))
print(" ".join(title.split()))
Expected outputpythonforbeginners
python for beginners

Strip other characters from the ends

strip() accepts a string of characters to remove instead of whitespace.

Strip other characters from the ends
line = "--total: 250--"
print(line.strip("-"))
Expected outputtotal: 250

Edge case: tabs and newlines survive replace()

replace(" ", "") leaves tabs and newlines behind, while split() removes them.

Edge case: tabs and newlines survive replace()
text = "a b\tc\nd"
print(repr(text.replace(" ", "")))
print(repr("".join(text.split())))
Expected output'ab\tc\nd'
'abcd'

Common mistakes

Expecting strip() to remove spaces in the middle

✗ Wrong

print("hello  world".strip())
hello world (the inner spaces are still there)

✓ Right

print(" ".join("hello  world".split()))

strip() only touches the two ends. Use replace() or " ".join(text.split()) for the middle.

Ignoring the return value

✗ Wrong

text = "  hi  "
text.strip()
print(repr(text))
' hi ' (the original is unchanged)

✓ Right

text = "  hi  "
text = text.strip()
print(repr(text))

Strings are immutable. Assign the result back.

Passing a string of characters and expecting a substring match

✗ Wrong

print("abcba".strip("ab"))
c (strip removes any of the listed characters, not the exact text "ab")

✓ Right

print("abcba".removeprefix("ab"))

strip(chars) treats its argument as a set of characters. To remove an exact prefix, use removeprefix().

How to Remove Whitespace from a String in Python: questions people ask

How do I remove spaces from a string in Python?

Use text.replace(" ", "") to delete every space, or text.strip() to remove only the spaces at the start and end.

How do I remove newline characters from a string?

Call text.strip() or text.rstrip("\n") to remove a trailing newline, or text.replace("\n", "") to remove all of them. Lines read from a file usually need rstrip().

What is the difference between strip(), lstrip() and rstrip()?

strip() trims both ends, lstrip() trims only the left side and rstrip() trims only the right side. None of them touch whitespace in the middle.

Keep learning

Step-by-step lessons:
Python StringsPython String MethodsPython Regular Expressions (regex)

Related:
Python String strip() MethodHow to Split a String into Words in PythonPython String replace() MethodHow to Read a File Line by Line in Python

More in working with text:
How to Reverse a String in PythonHow to Check if a String Contains a Substring in PythonHow to Split a String into Words in PythonHow to Compare Strings Ignoring Case in PythonHow to Pad a Number with Leading Zeros in PythonHow to Capitalize the First Letter of a String in Python See all →