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.'