简体   繁体   中英

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.

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

strip or lstrip functions can be used:

line = '   foo\nbar  spam'
while '  ' in line:
    line = line.replace('  ', ' ')
line = line.strip(' ')
text = [' '.join(i.split()) for i in text.split('\n') if not i.isspace()]
text = '\n'.join(text)                                                   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM