Editor

Clean and Normalize Whitespace

Advanced · Refactor · from Python Regular Expressions: Pattern Matching from Basics to Advanced

From the lesson: Python Regular Expressions: Pattern Matching from Basics to Advanced

Imagine you're working at a help desk and need to find every email address buried in thousands of support tickets. You could scan each line character by character, but that would take forever. Regular expressions let you describe the pattern of an email address, and Python finds every match for you.

Read the lesson

Refactor this messy string-cleaning code to use re.sub(). The function should: (1) replace all runs of multiple spaces/tabs with a single space, and (2) strip leading and trailing whitespace. The current code uses multiple chained .replace() calls -- make it cleaner with one regex substitution plus .strip().

import re
def clean_text(text):
# Current messy approach -- refactor to use re.sub()
text = text.replace(' ', ' ')
text = text.replace(' ', ' ')
text = text.replace('\t', ' ')
text = text.replace(' ', ' ')
text = text.strip()
return text
print(clean_text(' Hello world\t from Python '))

More Regex exercises

All Python exercises · 50 practice problems · Standard Library Essentials quiz