3

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
"""
Aman Deep
  • 187
  • 4
  • 11

3 Answers3

7

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()])
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
  • 2
    If the string doesn't end with a newline, this will add one (which may or may not be desirable). – ekhumoro Oct 13 '16 at 13:34
  • @ekhumoro Good observation. One could use this approach on a slice of the splitted lines that excludes the last and treat the last one differently. Depends on OP. – Moses Koledoye Oct 13 '16 at 13:37
  • 1
    It works but leaves a newline at the end of the string like what ekhumoro said. so, I use use rstrip() to remove that newline. works fine. – Aman Deep Oct 14 '16 at 03:19
4
import re
re.sub('\s+\n','\n',string)

Edit: better version from comments:

re.sub(r'\s+$', '', string, flags=re.M)
jatinderjit
  • 1,359
  • 8
  • 21
  • 1
    This will fail for lines which don't end with a newline. Better to use `re.sub(r'\s+$', '', string, flags=re.M)`. – ekhumoro Oct 13 '16 at 13:31
-1

As you can find here,

To remove all whitespace characters (space, tab, newline, and so on) you can use split then join:

sentence = ''.join(sentence.split())

or a regular expression:

import re
pattern = re.compile(r'\s+')
sentence = re.sub(pattern, '', sentence)
Community
  • 1
  • 1
Kian
  • 1,319
  • 1
  • 13
  • 23