Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Normalize whitespace in a string

Collapse all runs of whitespace into single spaces and trim ends.

Python practice10 minString PatternsBeginnerLast updated March 18, 2026

Problem statement

Write normalize_whitespace(s) that returns a new string where every contiguous run of whitespace characters (spaces, tabs, newlines, etc.) is replaced by a single ASCII space (' '), and leading/trailing whitespace is removed. If the input contains only whitespace, return an empty string.

Task

Implement a function that normalizes any whitespace sequences into single spaces and trims leading/trailing whitespace.

Examples

Multiple spaces

Input

normalize_whitespace(' Hello world ')

Output

Hello world

All extra spaces are collapsed to single spaces and trimmed.

Mixed whitespace

Input

normalize_whitespace('line1\nline2\tline3')

Output

line1 line2 line3

Newlines and tabs are converted to single spaces between tokens.

Input format

A call to normalize_whitespace(s) where s is a string.

Output format

The normalized string returned.

Constraints

Do not import external libraries; use built-in string methods. Aim for a solution that handles arbitrary Unicode whitespace correctly via built-in behavior.

Samples

Sample 1

Input

normalize_whitespace('already clean')

Output

already clean

No change needed.