Substitute multiple whitespace with single whitespace in Python


I have this string:

mystring = 'Here is  some   text   I      wrote   '

How can I substituate the double, triple (...) whitespaces to just one whitespace so that I get:

mystring = 'Here is some text I wrote'
8/4/2016 11:41:31 AM

Accepted Answer

A simple possibility (if you'd rather avoid REs) is

' '.join(mystring.split())

The split and join perform the task you're explicitly asking about -- plus, they also do the extra one that you don't talk about but is seen in your example, removing trailing spaces;-).

1/16/2010 3:54:24 PM

import re

re.sub('\s+', ' ', mystring).strip()

This will also substitute all tabs, newlines and other "whitespace-like" characters.

The strip() will remote any leading and trailing whitespaces.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow