Python Practice › RegEx Programs › Program 9
Collapse extra spaces
Write a Python program to replace runs of whitespace with a single space.
Output
'Python makes text cleaning easy'
Approach
re.sub(r"\s+", " ", text).strip().
Solution
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.