How to Remove Spaces from a String in Python
What you’ll build or solve
You’ll remove spaces from Python strings in a way that matches your actual input. .
When this approach works best
Removing spaces works well when you:
Learn Python on Mimo
- Clean user input before saving it, like a username or coupon code.
- Normalize identifiers, like turning
"AB 123 456"into"AB123456"for lookups. - Prepare values for comparisons, like matching data that differs only in spacing.
Avoid removing spaces when spacing carries meaning, like normal sentences you plan to display, fixed-width text formats, or anything where word boundaries matter.
Prerequisites
- Python installed
- You know what a string is
Step-by-step instructions
1) Remove leading and trailing whitespace
Use .strip() when the problem is extra whitespace at the start or end of a string.
raw=" Podgorica "
clean=raw.strip()
print(clean)
Left side only
raw=" left padded"
clean=raw.lstrip()
print(clean)
Right side only
raw="right padded "
clean=raw.rstrip()
print(clean)
What to look for: if results look unchanged, print repr(raw) first. Hidden characters show up as \t (tab) and \n (newline).
Swift
s="\tHello\nWorld "
print(repr(s))
2) Remove all regular space characters
If you want to delete regular space characters (" ") everywhere in the string, use .replace(" ", "").
s="AB 123 456"
no_spaces=s.replace(" ","")
print(no_spaces)
Alternative: split and join on spaces
This also removes normal spaces and can feel easier to read.
s="AB 123 456"
no_spaces="".join(s.split(" "))
print(no_spaces)
What to look for: split(" ") only targets normal spaces. Tabs and newlines remain.
3) Remove all whitespace types (spaces, tabs, newlines)
If input can contain tabs, newlines, or mixed whitespace, use split() with no argument. It splits on any whitespace and removes extra runs automatically.
s="AB\t123\n456"
no_whitespace="".join(s.split())
print(no_whitespace)
Option: use regex for an explicit rule
Use this if you already rely on regex in your project.
Python
importre
s="AB\t123\n456"
no_whitespace=re.sub(r"\s+","",s)
print(no_whitespace)
What to look for: \s matches many whitespace types, not just the normal space.
Examples you can copy
Example 1: Trim a form field before checking it
name=" Mina "
name=name.strip()
ifnotname:
print("Name is required.")
else:
print(f"Saved name:{name}")
Example 2: Normalize an ID for matching
stored_id="AB123456"
user_input="AB 123 456"
normalized=user_input.replace(" ","")
print(normalized==stored_id)# True
Example 3: Clean a copy-pasted token with line breaks and tabs
token="""
9f3a 12b7
00d1\t88aa
"""
token="".join(token.split())
print(token)
Example 4: Remove a non-breaking space from copied text
Sometimes text includes a non-breaking space (\u00A0) that looks like a normal space.
s="AB\u00A0123"
clean=s.replace("\u00A0","")
print(clean)
Example 5: Normalize spacing without deleting all spaces
This keeps the text readable while collapsing runs of whitespace to a single space.
Python
importre
s="Hello from Boston"
normalized=re.sub(r"\s+"," ",s).strip()
print(normalized)
Common mistakes and how to fix them
Mistake 1: Using strip() and expecting it to remove spaces in the middle
What you might do:
s="AB 123 456"
print(s.strip())
Why it fails: strip() only removes whitespace at the start and end.
Fix:
Bash
print(s.replace(" ",""))
If the input may contain tabs or newlines:
Bash
print("".join(s.split()))
Mistake 2: Removing " " but missing tabs, newlines, or non-breaking spaces
What you might do:
Swift
s="AB\t123\n456"
print(s.replace(" ",""))
Why it fails: tabs and newlines are different characters.
Fix:
Bash
print("".join(s.split()))
For copied text with \u00A0:
Bash
s="AB\u00A0123"
print(s.replace("\u00A0",""))
Troubleshooting
If you see AttributeError: 'NoneType' object has no attribute 'strip', check if your value is None before calling string methods.
If your result looks unchanged, print repr(your_string) to reveal \t, \n, or \u00A0.
If comparisons still fail after cleaning, confirm you compare the cleaned value, not the original variable.
If replace(" ", "") misses characters, switch to "".join(s.split()) to remove all whitespace types.
If removing spaces makes text unreadable, use the normalization example to keep single spaces between words.
Quick recap
- Use
.strip()to remove whitespace at the start and end. - Use
.replace(" ", "")to remove normal spaces everywhere. - Use
"".join(s.split())to remove spaces, tabs, and newlines. - Use
repr()when hidden whitespace makes results confusing. - Use regex normalization when you want readable text with consistent spacing.
Join 35M+ people learning for free on Mimo
4.8 out of 5 across 1M+ reviews
Check us out on Apple AppStore, Google Play Store, and Trustpilot