如何在Python中删除带或不带空格的空行

38 python string

我有一个大字符串,我用换行符分割.如何删除所有空行(仅限空格)?

伪代码:

for stuff in largestring:
   remove stuff that is blank
Run Code Online (Sandbox Code Playgroud)

gim*_*mel 53

尝试列表理解和string.strip():

>>> mystr = "L1\nL2\n\nL3\nL4\n  \n\nL5"
>>> mystr.split('\n')
['L1', 'L2', '', 'L3', 'L4', '  ', '', 'L5']
>>> [line for line in mystr.split('\n') if line.strip() != '']
['L1', 'L2', 'L3', 'L4', 'L5']
Run Code Online (Sandbox Code Playgroud)

  • 您可以通过省略!=''简单地"if line.strip()"来缩短它 (11认同)
  • +1有助于显示中间结果. (4认同)

Nul*_*ion 46

使用正则表达式:

if re.match(r'^\s*$', line):
    # line is empty (has only the following: \t\n\r and whitespace)
Run Code Online (Sandbox Code Playgroud)

使用正则表达式+ filter():

filtered = filter(lambda x: not re.match(r'^\s*$', x), original)
Run Code Online (Sandbox Code Playgroud)

如在键盘上看到的那样.

  • gimel的解决方案,随后重新加入文本,提供了更好的性能.我在一个小文本上比较了这两个解决方案(10行,如果3个是空白的).结果如下:正则表达式:1000循环,最佳3:452 us循环`; join,split&strip:`100000循环,最好3:每循环一次5.41 us (3认同)
  • 感谢所有的结果,但是,这个解决方案正是我一直在寻找的!非常感谢 (2认同)

Reg*_*isz 16

我也试过regexp和列表解决方案,列表一个更快.

这是我的解决方案(通过以前的答案):

text = "\n".join([ll.rstrip() for ll in original_text.splitlines() if ll.strip()])
Run Code Online (Sandbox Code Playgroud)


nmi*_*els 10

编辑:哇,我想省略显而易见的不行.

lines = bigstring.split()
lines = [line for line in lines if line.strip()]
Run Code Online (Sandbox Code Playgroud)

  • @Walter:实际上,如果你使用'Line \n \nLine \n'.split()就像你应该的那样,那就可以了. (2认同)

小智 9

令人惊讶的是,没有建议使用多行 re.sub (哦,因为你已经分割了你的字符串......但为什么?):

>>> import re
>>> a = "Foo\n \nBar\nBaz\n\n   Garply\n  \n"
>>> print a
Foo

Bar
Baz

        Garply


>>> print(re.sub(r'\n\s*\n','\n',a,re.MULTILINE))
Foo
Bar
Baz
        Garply

>>> 
Run Code Online (Sandbox Code Playgroud)


Ook*_*ker 5

如果你不愿意尝试正则表达式(你应该),你可以使用这个:

s.replace('\n\n','\n')
Run Code Online (Sandbox Code Playgroud)

重复几次以确保没有空白行.或者链接命令:

s.replace('\n\n','\n').replace('\n\n','\n')
Run Code Online (Sandbox Code Playgroud)

  • 例如,您可能想要使用正则表达式。当您编码时,“确保重复几行”并不是一个好主意,因为您可能会留下未解决的问题或浪费时间运行比需要的次数更多的东西。 (2认同)

归档时间:

查看次数:

124865 次

最近记录:

6 年,1 月 前