Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 512
I159 Avatar asked Dec 16 '22 12:12

I159


2 Answers

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

like image 160
jamylak Avatar answered Dec 18 '22 01:12

jamylak


strip or lstrip functions can be used:

line = '   foo\nbar  spam'
while '  ' in line:
    line = line.replace('  ', ' ')
line = line.strip(' ')
like image 42
Artsiom Rudzenka Avatar answered Dec 18 '22 02:12

Artsiom Rudzenka