← Back to all snippets
PYTHON

Replacing Multiple Spaces with a Single Space

Clean up user input or text data by replacing sequences of multiple whitespace characters with a single space using Python's `re` module.

import re

def consolidate_spaces(text):
    return re.sub(r'\s+', ' ', text).strip()

text_with_extra_spaces = "  This is   a string    with   too many   spaces.  "
cleaned_text = consolidate_spaces(text_with_extra_spaces)
print(cleaned_text) # "This is a string with too many spaces."
How it works: This Python function utilizes the `re.sub()` method to replace one or more whitespace characters (`\s+`) with a single space. The `strip()` method is then called to remove any leading or trailing whitespace that might result from the substitution at the beginning or end of the string, ensuring a clean output.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs