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(' ')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With