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 lessonRefactor 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().
More Regex exercises
- Find a Phone NumberIntermediate
- Extract All HashtagsIntermediate
- Predict the Regex OutputIntermediate
- Censor Credit Card NumbersIntermediate
- Fix the Email ValidatorIntermediate
- Parse a Log EntryIntermediate
All Python exercises · 50 practice problems · Standard Library Essentials quiz