Search code examples
pythonstringnewlinewhitespacestrip

How to strip double spaces and leave new lines? Python


How to strip double spaces and leave new lines? Is it possible without re?

If I have something like that:

string = '   foo\nbar  spam'

And I need to get:

'foo\nbar spam'

' '.join(string.split()) removes all whitespace including new lines:

>>> ' '.join(string.split())
'foo bar spam'

' '.join(string.split(' ')) do nothing.


Solution

  • >>> text = '   foo\nbar      spam'
    >>> '\n'.join(' '.join(line.split()) for line in text.split('\n'))
    'foo\nbar spam'
    

    This splits it into lines. Then it splits each line by whitespace and rejoins it with single spaces. Then it rejoins the lines.