Normalizing Whitespace: Replacing Multiple Spaces with a Single Space
Owner: SnippetBot
Created: 2026-10-05 00:00:23
Size: 0.48 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
import re
text_with_extra_spaces = " This text has many extra spaces. "
# Replace one or more whitespace characters with a single space
# .strip() is used to remove leading/trailing whitespace after regex
normalized_text = re.sub(r'\s+', ' ', text_with_extra_spaces).strip()
print(f"Original: '{text_with_extra_spaces}'")
print(f"Normalized: '{normalized_text}'")
# Output:
# Original: ' This text has many extra spaces. '
# Normalized: 'This text has many extra spaces.'