How to Remove Spaces From a String in Python (Complete 2026 Guide)
import re
clean = re.sub(r”\s+”, “”, s) # Remove all whitespace (spaces, tabs, newlines)
That single line removes all whitespace characters from a Python string and is the most robust answer for most real-world use cases.
What Does “Remove Spaces” Mean in Python?
They usually mean one of these:
- Remove only space characters
- Remove all whitespace including tabs and newlines
- Remove extra spaces but keep words separated
- Trim spaces from start or end
Understanding the difference is critical for choosing the correct method.
| Goal | Best Method |
| Remove all whitespace | re.sub(r”\s+”, “”, s) |
| Remove only spaces | s.replace(” “, “”) |
| Remove extra spaces but keep words | ” “.join(s.split()) |
| Trim leading/trailing spaces | s.strip() |
| Fast deletion of known characters | s.translate() |
1. remove spaces python using replace()
The replace() method replaces occurrences of a substring with another substring.
To remove literal spaces:
s = "W hi te space"
newStr = s.replace(" ", "")
print(newStr)
Output:
Whitespace
Best for:
- Simple space removal
- Clean ASCII input
- High performance needs
Not suitable for:
- Tabs \t
- Newlines \n
- Unicode whitespace
2. remove whitespace python using split() and join()
This technique removes whitespace by splitting and rejoining.
s = "W hi te space"
newStr = "".join(s.split())
print(newStr)
Output:
Whitespace
If used on a sentence:
s = "W hi te space need to remove"
newStr = "".join(s.split())
print(newStr)
Output:
Whitespaceneedtoremove
Important:
- Removes all whitespace between words
- Words will be concatenated
To normalize instead:
normalized = " ".join(s.split())
This keeps words separated but removes extra spaces.
3. remove spaces python using translate()
translate() is very efficient for deleting specific characters.
s = "W hi te space"
newStr = s.translate(str.maketrans('', '', ' '))
print(newStr)
Output:
Whitespace
Advantages:
- Very fast
- Efficient for large strings
- Can remove multiple characters at once
Example removing spaces and tabs:
s.translate(str.maketrans('', '', ' \t'))
4. trim whitespace using lstrip() and rstrip()
These methods remove whitespace only from ends.
lstrip()
string = " This string need to remove whitespace from left side"
string_new = string.lstrip()
print(string_new)
rstrip()
string = "This string need to remove whitespace from right side "
string_new = string.rstrip()
print(string_new)
Important:
- They do not remove internal spaces
- Use strip() to remove both ends
5. remove whitespace using isspace() loop
isspace() checks if a character is whitespace.
s = " This s tring needs to remove whitespace "
result = ""
for ch in s:
if not ch.isspace():
result += ch
print(result)
Output:
Thisstringneedstoremovewhitespace
Use when:
- Custom filtering is required
- Educational demonstration
- Special character control logic
Not recommended for performance-critical systems.
6. remove whitespace python using Regex and itertools
Regex is the most powerful and flexible method.
import re
import itertools
s = " This String Ne eds to remo ve white space "
clean = re.sub(r"\s+", "", s)
print(clean)
Output:
ThisStringNeedstoremovewhitespace
You generally do not need itertools if using regex correctly.
Regex is ideal when:
- Input is unpredictable
- Text may include tabs/newlines
- Cleaning user input
- Data preprocessing pipelines
7. remove spaces using map() and lambda()
s = " This Str ing i gonna tes t with map and lambda "
s = ''.join(map(lambda x: x.strip(), s.split()))
print(s)
Output:
ThisStringigonnatestwithmapandlambda
Readable but not faster than built-in alternatives.
8. remove spaces using NumPy
Useful in data science workflows.
import numpy as np
string = " Te st String "
finalStr = np.char.replace(string, ' ', '')
print(finalStr)
Output:
TestString
Best for:
- Vectorized operations
- Processing arrays of strings
- Scientific computing
Not ideal for simple string operations.
Performance Benchmark Comparison
Based on timeit benchmarking (synthetic 20k+ char string):
| Method | Speed Rank | Use Case |
| translate | Fastest | Delete specific characters |
| replace | Very fast | Remove literal spaces |
| split + join | Medium | Token-based removal |
| regex (re.sub) | Slower | Most robust solution |
Key Insight:
- For performance + simplicity: use replace()
- For correctness across all whitespace types: use re.sub()
- For formatting normalization: use ” “.join(s.split())
Always benchmark in your environment if performance matters.
Which Method Should You Use?
Use this decision guide:
If you need:
- Remove all whitespace → re.sub(r”\s+”, “”, s)
- Remove only spaces → s.replace(” “, “”)
- Normalize spacing → ” “.join(s.split())
- Trim ends → s.strip()
- High-performance bulk deletion → translate()
- Data science pipelines → NumPy
People Also Ask(And You Should Too!)
Q) How do I remove all spaces from a string in Python?
A) Use:
s.replace(" ", "")
or for all whitespace:
re.sub(r"\s+", "", s)
Q) How do I remove extra spaces but keep words separated?
A) Use:
” “.join(s.split())
Q) Which method is fastest for removing spaces?
A) translate() and replace() are typically fastest for simple ASCII space removal.
Q) Does replace remove tabs and newlines?
A) No. Use sub(r”\s+”, “”, s) for full whitespace removal.
Q) How do I remove leading and trailing whitespace?
A) Use:
s.strip()
Q) How do I remove only leading spaces in Python?
A) Use lstrip() to remove whitespace from the left side only.
s = " Hello"
print(s.lstrip())
This does not affect spaces inside or at the end of the string.
How do I remove only trailing spaces in Python?
Use rstrip() to remove whitespace from the right side.
s = "Hello "
print(s.rstrip())
Q) How do I remove both leading and trailing spaces in Python?
A) Use strip():
s = " Hello "
print(s.strip())
This removes whitespace only from the beginning and end.
Q) How do I remove multiple consecutive spaces in Python?
A) To collapse multiple spaces into a single space:
normalized = " ".join(s.split())
This keeps word separation intact while removing extra spacing.
Q) How do I remove tabs and newline characters from a string in Python?
A) Use regex for complete whitespace removal:
import re
clean = re.sub(r"\s+", "", s)
This removes spaces, tabs (\t), and newlines (\n).
Q) How do I remove spaces from a user input string in Python?
A) user_input = input(“Enter text: “)
clean = user_input.replace(" ", "")
For production-grade cleaning, use regex to remove all whitespace types.
Q) How do I remove non-breaking spaces in Python?
A) Non-breaking spaces (\u00A0) are not removed by replace(” “, “”).
Use:
import re
clean = re.sub(r"\s+", "", s)
or explicitly:
s.replace("\u00A0", "")
Q) What is the fastest way to remove spaces from a string in Python?
A) For removing only literal spaces:
s.translate(str.maketrans('', '', ' '))
For correctness across all whitespace:
re.sub(r"\s+", "", s)
Performance depends on input size and character variety.
Q) How do I remove spaces from a list of strings in Python?
A) Using list comprehension:
strings = ["Hello World", "Python Code"]
cleaned = [s.replace(" ", "") for s in strings]
Using NumPy for large datasets:
import numpy as np
np.char.replace(array, " ", "")
Q) How do I remove spaces and special characters in Python?
To remove spaces and non-alphanumeric characters:
import re
clean = re.sub(r"[^a-zA-Z0-9]", "", s)
Useful for:
Data cleaning
Slug generation
Input validation
Q) How do I remove extra spaces between words but keep one space?
A) clean = ” “.join(s.split())
This is ideal for formatting user-generated content.
Q) How do I check if a string contains only whitespace in Python?
A) Use isspace():
s.isspace()
Returns True if the string contains only whitespace characters.
Q) How do I remove spaces from a CSV column in Python?
A) Using pandas:
df["column"] = df["column"].str.replace(" ", "", regex=False)
For full whitespace removal:
df["column"] = df["column"].str.replace(r"\s+", "", regex=True)
This helps target data-cleaning queries.
Q) How do I remove spaces from filenames in Python?
A) import os
new_name = filename.replace(" ", "_")
os.rename(filename, new_name)
Useful for automation scripts and DevOps workflows.
Q) How do I remove spaces in Python without using regex?
A) You can use:
“”.join(s.split())
or
s.replace(" ", "")
Regex is optional unless handling complex whitespace cases.
Conclusion
Python provides multiple methods to remove spaces and whitespace from strings, each serving different purposes.
- replace() is simple and fast.
- translate() is efficient for deleting known characters.
- split() + join() is excellent for normalization.
- re.sub() is the most robust solution.
- strip() methods handle trimming.
- NumPy is useful in vectorized workflows.
The correct choice depends on your use case, performance needs, and data complexity.