How to Remove Duplicate Adjacent Spaces in Python

This Python function collapses any sequence of two or more adjacent spaces into a single space, preserving all other characters.

Easy Python 3.6+ Aug 9, 2026 Strings & text 12 views 0 copies

Python code

19 lines
Python 3.6+
def remove_duplicate_adjacent_spaces(text):
    """Replace sequences of 2+ spaces with a single space."""
    result = []
    prev_was_space = False
    for char in text:
        if char == " ":
            if not prev_was_space:
                result.append(char)
            prev_was_space = True
        else:
            result.append(char)
            prev_was_space = False
    return "".join(result)


if __name__ == "__main__":
    sample = "This  has   multiple    spaces   between words."
    print(repr(sample))
    print(repr(remove_duplicate_adjacent_spaces(sample)))

Output

stdout
'This  has   multiple    spaces   between words.'
'This has multiple spaces between words.'

How it works

The function iterates through each character in the input string, tracking whether the previous character was a space. When a space is encountered, it is only added to the result if the previous character was not a space, effectively collapsing consecutive spaces into one. Non-space characters are always appended and reset the prev_was_space flag. This manual approach is explicit and efficient, running in O(n) time with a constant memory overhead, and avoids the potential pitfalls of regex patterns for beginners.

Common mistakes

  • Using `str.split()` and `join` which also removes leading/trailing spaces and collapses all whitespace characters, not just spaces.
  • Forgetting to preserve spaces at the start or end of the string when using a regex replacement.
  • Using `text.replace(' ', ' ')` only handles exactly two spaces, not three or more.

Variations

  1. Use `re.sub(r' {2,}', ' ', text)` for a concise one-liner.
  2. Use `' '.join(text.split())` to collapse all whitespace, but this also strips leading/trailing spaces.

Real-world use cases

  • Cleaning up user input in a web form before saving to a database to avoid inconsistent spacing.
  • Normalizing text extracted from PDFs or OCR where multiple spaces are common artifacts.
  • Preprocessing log messages or command output to standardize spacing for easier parsing.

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.