Normalize Internal Whitespace

Medium ⏱ 12 min 46% acceptance ★★★★★ 4.7
Write normalize_whitespace(s) that collapses every run of internal whitespace (spaces, tabs) down to a single space, and also trims leading/trailing whitespace.

Examples

Example 1
Input
s = '  Hello   World  '
Output
'Hello World'
Explanation

Leading/trailing spaces trimmed, internal double-space collapsed to one.

Example 2
Input
s = 'This   is    a   test'
Output
'This is a test'
Explanation

Every internal whitespace run becomes exactly one space.

Constraints

  • 0 <= len(s) <= 10^4

Topics

StringsWhitespace Handling

Companies

MicrosoftAdobe

Hints

Hint 1

`s.split()` with no arguments already tokenizes on any whitespace run, discarding empties.

Hint 2

Rejoin the tokens with a single space.

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