Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/351.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 删除换行前的空格_Python - Fatal编程技术网

Python 删除换行前的空格

Python 删除换行前的空格,python,Python,我需要删除整个字符串中换行符之前的所有空格 string = """ this is a line \n this is another \n """ 输出: string = """ this is a line\n this is another\n """ 编辑:来自评论的更好版本: re.sub(r'\s+$', '', string, flags=re.M) 您可以将字符串拆分为几行,使用rstrip去除右侧的所有空白,然后在每行末尾添加新行: '

我需要删除整个字符串中换行符之前的所有空格

string = """
this is a line       \n
this is another           \n
"""
输出:

string = """
this is a line\n
this is another\n
"""
编辑:来自评论的更好版本:

re.sub(r'\s+$', '', string, flags=re.M)
您可以将字符串拆分为几行,使用
rstrip
去除右侧的所有空白,然后在每行末尾添加新行:

''.join([line.rstrip()+'\n' for line in string.splitlines()])
如你所见

要删除所有空白字符(空格、制表符、换行符等),可以使用“先拆分后联接”:

sentence = ''.join(sentence.split())
或正则表达式:

import re
pattern = re.compile(r'\s+')
sentence = re.sub(pattern, '', sentence)

对于不以换行符结尾的行,此操作将失败。最好使用
re.sub(r'\s+$','',string,flags=re.M)
。如果字符串没有以换行符结尾,这将添加一个(这可能是可取的,也可能不是可取的)。@ekhumaro观察得很好。可以在分割线的切片上使用这种方法,排除最后一条线,并以不同的方式处理最后一条线。取决于OP。它可以工作,但在字符串的末尾留下一条新行,就像Ekhumaro说的那样。因此,我使用rstrip()删除该换行符。工作正常。但是他不想替换所有的空格。你说的是
str.replace()
而不是
str.sub()
OP不想删除字符串中的所有空格,只是在行的末尾。您的解决方案删除了所有空格,即使是句子中的单词之间。
import re
pattern = re.compile(r'\s+')
sentence = re.sub(pattern, '', sentence)