Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove spaces before newlines

Tags:

python

I need to remove all spaces before the newline character throughout a string.

string = """
this is a line       \n
this is another           \n
"""

output:

string = """
this is a line\n
this is another\n
"""
like image 294
Aman Deep Avatar asked Jun 17 '26 02:06

Aman Deep


2 Answers

You can split the string into lines, strip off all whitespaces on the right using rstrip, then add a new line at the end of each line:

''.join([line.rstrip()+'\n' for line in string.splitlines()])
like image 162
Moses Koledoye Avatar answered Jun 19 '26 16:06

Moses Koledoye


import re
re.sub('\s+\n','\n',string)

Edit: better version from comments:

re.sub(r'\s+$', '', string, flags=re.M)
like image 26
jatinderjit Avatar answered Jun 19 '26 17:06

jatinderjit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!