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
"""
可以拆分串入线,采用剥离右侧所有空格rstrip
,然后在每行的末尾添加一个新行:
''.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)
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)
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.