🚀 Supercharge your YouTube channel's growth with AI.
Try YTGrowAI FreeRemove Spaces in String Python

Removing spaces from a Python string means choosing which spaces or whitespace characters to change. Python string methods change selected whitespace in a string.
The example shows the output for removing ordinary spaces and for removing all whitespace.
TL;DR
Use replace(” “, “”) to delete ordinary spaces, “”.join(text.split()) to delete whitespace characters, and strip() to trim only the edges.
- Choose replacement when tabs and line breaks must stay.
- Use split and join when every whitespace separator should disappear.
- Use strip, lstrip or rstrip when internal word spacing must stay.
What Does Removing Spaces Mean in Python?
Removing spaces in Python means deleting selected whitespace characters, collapsing them, or trimming them from a string’s ends. These are different transformations, so the intended result determines the method.
For example, removing every separator from “Ada Lovelace” produces “AdaLovelace”. That result may suit a compact identifier but not a name intended for display.
The built-in str methods cover common cases. Python’s string documentation defines strip() as edge removal and replace() as substring replacement. The AskPython guides to string methods and split() explain those operations in more detail.
How to Remove Spaces from a Python String Step by Step
I ran one example containing ordinary spaces, a tab, a newline and an empty string. Its output makes the scope of each operation visible.
Step 1: Delete ordinary spaces with replace()
Call replace(” “, “”) when the literal space between characters should disappear. It leaves tabs and line breaks alone because they are different characters from an ordinary space.
Step 2: Remove all whitespace with split() and join()
With no delimiter, split() treats runs of whitespace as separators. Joining the resulting pieces with an empty string removes spaces, tabs and newlines. Joining with a single space instead collapses runs while preserving word boundaries.
A specified delimiter is different from whitespace splitting. It matches that exact character and can leave empty list items between repeated delimiters. This is useful when a format assigns meaning to a particular separator, such as a pipe-delimited record.
The split result is a list of strings. Join belongs to the separator, which means the separator appears between each pair of items. If the pieces came from numeric values, convert them to strings before joining.
String methods return new values rather than changing their input. Keep the source and result in separate variables when both forms are needed later.
Step 3: Trim only the edges
Use strip() for both ends, lstrip() for the beginning, or rstrip() for the end. These methods keep internal whitespace, which is useful when cleaning input before display or comparison.
text = " Ada Lovelace\t wrote\ncode "
print("original:", repr(text))
print("remove ordinary spaces:", repr(text.replace(" ", "")))
print("remove all whitespace:", repr("".join(text.split())))
print("collapse whitespace:", repr(" ".join(text.split())))
print("trim edges:", repr(text.strip()))
print("empty input:", repr("".join("".split())))
Run the example from a file with python3 whitespace_demo.py. Its output was:
original: ‘ Ada Lovelace\t wrote\ncode ‘
remove ordinary spaces: ‘AdaLovelace\twrote\ncode’
remove all whitespace: ‘AdaLovelacewrotecode’
collapse whitespace: ‘Ada Lovelace wrote code’
trim edges: ‘Ada Lovelace\t wrote\ncode’
empty input: ”

The final line confirms that empty input produces an empty string rather than an exception.
Printing the result does not change a variable. Assign a returned string before passing the cleaned value to another function or storing it.
I compared empty and single-space separators in the example. The first joins tokens directly, while the second keeps a readable boundary. A tab separator is another option when a downstream format expects tab-delimited text.
Edge Cases When Removing Whitespace
The table maps common input cases to their symptoms and fixes.
| Case | What can go wrong | Fix |
|---|---|---|
| Repeated spaces in display text | Deleting all separators joins separate words. | Join the pieces from whitespace splitting with one ordinary space. This also trims the ends. |
| Whitespace on one edge | Removing internal separators changes names or labels. | Use left trimming for the beginning or right trimming for the end. |
| Only selected characters | A whitespace-wide operation removes tabs and line breaks you meant to retain. | Build a deletion mapping with str.maketrans(“”, “”, ” ,”) and apply it with translate(). The third argument names the characters to delete. |
| Comma and nearby spaces | Deleting the comma can merge adjacent fields. | Replace a comma followed by a space with a comma when the boundary should stay. CSV can contain quoted commas, so use Python’s csv module rather than splitting a CSV record by hand. |
| Cleaned value seems unchanged | String methods return a new string instead of editing the original. | Assign the result, for example cleaned = text.strip(), then use cleaned where needed. |
Regular expressions handle rules that need a broader match. The standard library’s re documentation describes substitution. A whitespace expression can remove matching runs, although built-in methods state these common transformations more clearly.
A character-by-character loop using isspace() can also filter whitespace. It gives explicit control over each character, but it adds iteration and reconstruction code when split and join already express the operation. Use that approach when the filtering rule needs per-character decisions, not merely to remove all whitespace.
A regular expression is another option when the rule is defined by a more complex match. It can be useful when whitespace is only part of a larger substitution rule. For a plain whitespace cleanup, the built-in string methods avoid importing the regular-expression module and make the chosen result explicit.
Translation suits a fixed set of characters, such as spaces and commas, because its deletion table names exactly what disappears. It is less suited to collapsing a variable-length run into one separator. Use joining for that transformation instead.
Delimited text needs special care. Removing a comma changes the boundary between fields, while removing spaces around a comma can leave the fields distinct. For CSV files, quoted fields may contain commas, so use the standard library parser rather than treating each comma as a separator.
Conclusion
Match the method to the characters you want to remove: replace a literal space, split and join for all whitespace, or strip the edges. Check whether the output should retain word boundaries before using an empty separator.
FAQ
These answers distinguish deleting spaces from trimming or collapsing them.
How do I remove all spaces from a string in Python?
Use “”.join(text.split()) to remove whitespace characters, or text.replace(” “, “”) to remove ordinary spaces only.
How do I remove extra spaces but keep one between words?
Use ” “.join(text.split()) to collapse whitespace runs to one ordinary space and trim the edges.
Does strip() remove spaces between words?
No. strip() removes whitespace at the beginning and end of a string, not between words.


