How to Remove Spaces from String in Python Easily
To remove all spaces from a string in Python, use
str.replace(' ', ''). To remove spaces only at the start and end, use str.strip().Syntax
Here are common ways to remove spaces from strings in Python:
str.replace(' ', ''): Removes all spaces inside the string.str.strip(): Removes spaces only at the start and end of the string.str.lstrip(): Removes spaces only at the start (left side).str.rstrip(): Removes spaces only at the end (right side).
python
string.replace(' ', '') string.strip() string.lstrip() string.rstrip()
Example
This example shows how to remove all spaces and how to remove only leading and trailing spaces.
python
text = ' Hello World ' # Remove all spaces no_spaces = text.replace(' ', '') # Remove spaces only at start and end trimmed = text.strip() print('Original:', repr(text)) print('No spaces:', repr(no_spaces)) print('Trimmed:', repr(trimmed))
Output
Original: ' Hello World '
No spaces: 'HelloWorld'
Trimmed: 'Hello World'
Common Pitfalls
One common mistake is using strip() when you want to remove all spaces inside the string. strip() only removes spaces at the start and end, not in the middle.
Another mistake is forgetting that replace() is case-sensitive and only replaces exact matches.
python
text = ' Hello World ' # Wrong: strip() does not remove spaces inside wrong = text.strip() # Right: replace() removes all spaces right = text.replace(' ', '') print('Wrong:', repr(wrong)) print('Right:', repr(right))
Output
Wrong: 'Hello World'
Right: 'HelloWorld'
Quick Reference
Use this quick guide to choose the right method:
| Method | What it does | Example |
|---|---|---|
str.replace(' ', '') | Removes all spaces anywhere in the string | 'Hello World' → 'HelloWorld' |
str.strip() | Removes spaces only at start and end | ' Hello ' → 'Hello' |
str.lstrip() | Removes spaces only at the start | ' Hello ' → 'Hello ' |
str.rstrip() | Removes spaces only at the end | ' Hello ' → ' Hello' |
Key Takeaways
Use str.replace(' ', '') to remove all spaces inside a string.
Use str.strip() to remove spaces only at the start and end.
strip() does not remove spaces inside the string.
Remember lstrip() and rstrip() remove spaces only on one side.
Always check which spaces you want to remove before choosing a method.