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.
Python code
19 linesdef 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
'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
- Use `re.sub(r' {2,}', ' ', text)` for a concise one-liner.
- 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
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.