Collapse extra spaces

EasyRegEx Programs · 9 of 20

Write a Python program to replace runs of whitespace with a single space.

Advertisement
Output
'Python makes text cleaning easy'

Approach

  1. re.sub(r"\s+", " ", text).strip().

Solution

Python
import re text = "  Python    makes\ttext \n cleaning   easy  "print(repr(re.sub(r"\s+", " ", text).strip()))
Output
'Python makes text cleaning easy'

Learn the concept

New to this topic? Read the lesson, then come back.

More regex programs

← All 20 RegEx Programs

Leave a Comment