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
"""
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()])
import re
re.sub('\s+\n','\n',string)
Edit: better version from comments:
re.sub(r'\s+$', '', string, flags=re.M)
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