Suppose this is the string:
The fox jumped over the log.
It would result in:
The fox jumped over the log.
What is the simplest, 1-2 liner that can do this? Without splitting and going into lists...
Suppose this is the string:
The fox jumped over the log.
It would result in:
The fox jumped over the log.
What is the simplest, 1-2 liner that can do this? Without splitting and going into lists...
>>> import re
>>> re.sub(' +',' ','The quick brown fox')
'The quick brown fox'
import re
s = "The fox jumped over the log."
re.sub("\s\s+" , " ", s)
Similar to the previous solutions, but more specific: replace two or more spaces with one:
>>> import re
>>> s = "The fox jumped over the log."
>>> re.sub('\s{2,}', ' ', s)
'The fox jumped over the log.'
Have to agree with Paul McGuire's comment above. To me,
' '.join(the_string.split())
is vastly preferable to whipping out a regex. My measurements (Linux, Python 2.5) show the split-then-join to be almost 5 times faster than doing the "re.sub(...)", and still 3 times faster if you precompile the regex once and do the operation multiple times. And it is by any measure easier to understand -- much more pythonic.