[英]Remove spaces before newlines
我需要删除整个字符串中的换行符之前的所有空格。
string = """
this is a line \n
this is another \n
"""
输出:
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)
编辑:评论的更好版本:
re.sub(r'\s+$', '', string, flags=re.M)
你可以在这里找到,
要删除所有空白字符(空格,制表符,换行符等),您可以使用拆分然后加入:
sentence = ''.join(sentence.split())
或正则表达式:
import re
pattern = re.compile(r'\s+')
sentence = re.sub(pattern, '', sentence)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.