How to Replace Multiple Spaces with a Single Space in Python
This snippet uses the `re` module to collapse runs of consecutive spaces in a string into a single space, cleaning up whitespace.
Python code
11 linesimport re
def collapse_spaces(text):
"""Replace multiple consecutive spaces with a single space."""
return re.sub(r' +', ' ', text)
if __name__ == "__main__":
sample = "This has multiple spaces between words."
result = collapse_spaces(sample)
print(f"Original: '{sample}'")
print(f"Collapsed: '{result}'")
Output
Original: 'This has multiple spaces between words.'
Collapsed: 'This has multiple spaces between words.'
How it works
The code uses the regular expression +, which matches one or more literal space characters. The re.sub function replaces every match with a single space. This approach is efficient for strings with many spaced segments and only affects spaces, not tabs or newlines. For more robust whitespace normalization, consider using re.sub(r'\s+', ' ', text) to collapse all whitespace types.
Common mistakes
- Using `str.replace(' ', ' ')` which only removes double spaces, not triple or more.
- Using `' '.join(text.split())` which also collapses newlines and tabs, not just spaces.
- Forgetting to escape the backslash if using `\s` in the regex.
Variations
- Use `' '.join(text.split())` to collapse all whitespace types (spaces, tabs, newlines).
- Use `re.sub(r'\s+', ' ', text)` to replace runs of any whitespace with a single space.
Real-world use cases
- Normalizing user input in a search bar so extra spaces don't affect query results.
- Cleaning text extracted from PDFs or OCR where extra spaces are common.
- Preparing string data for logging or storage in databases to maintain consistent formatting.
Sponsored
More from Strings & text
- Automatically Detect Weak Passwords from Large Password Lists in Python easy
- Build CSV row from Python list with proper quoting easy
- Build a Secure Password Strength Checker in Python easy
- Convert Natural Language Dates to Datetime in Python medium
- Count Characters, Words, and Lines in Python Text easy
- Extract Data from Strings in Python: Beginner's Guide easy
Keep learning
Related tutorials and quizzes for this topic.