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.

Easy Python 3.9+ Aug 9, 2026 Strings & text 15 views 0 copies

Python code

11 lines
Python 3.9+
import 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

stdout
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

  1. Use `' '.join(text.split())` to collapse all whitespace types (spaces, tabs, newlines).
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Strings & text

Related tutorials and quizzes for this topic.