Collapse Runs of Whitespace

Easy ⏱ 8 min 73% acceptance ★★★★★ 4.9
Write normalize(text) replacing every run of whitespace (spaces, tabs, newlines) with a single space and trimming the ends — re.sub(r'\s+', ' ', ...) then strip().

Examples

Example 1
Input
normalize('  hello\t\tworld \n twice  ')
Output
'hello world twice'
Explanation

All whitespace runs collapse to single spaces.

Constraints

  • Tabs and newlines count as whitespace.
  • No leading/trailing spaces in the result.

Topics

Regular Expressionssub

Companies

GrammarlyNotionZoho

Hints

Hint 1

\s matches all whitespace classes.

Hint 2

Chain .strip() after the sub.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.