tags:

views:

112

answers:

2

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'

Thanks.

+4  A: 
import re

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

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

the strip() in the end will cut off any trailing whitespaces, as you requested.

hroest
+7  A: 

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;-).

Alex Martelli
Oh cool, I was fumbling with a similar solution, but using split(' ') and then a filter to remove empty elements. I never knew split with no arguments worked like this. This is also much faster, timeit.py gives me around 0.74usec for this, versus 5.75usec for regular expressions.
Roman Stolper
@Roman, yes, `x.split()` (and `x.split(None)`) splits on _sequences of whitespace_ (including tabs, newlines, etc, like re's `\s`) of length 1+ -- and it's pretty fast indeed. So, always glad to help!
Alex Martelli