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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3711856/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:22:42  来源:igfitidea点击:

How to remove empty lines with or without whitespace in Python

pythonstring

提问by

I have large string which I split by newlines. How can I remove all lines that are empty, (whitespace only)?

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

pseudo code:

伪代码:

for stuff in largestring:
   remove stuff that is blank

采纳答案by NullUserException

Using regex:

使用正则表达式:

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

Using regex + filter():

使用正则表达式 + filter()

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

As seen on codepad.

正如在键盘上看到的那样。

回答by gimel

Try list comprehension and string.strip():

尝试列表理解和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']

回答by nmichaels

Edit: Wow, I guess omitting the obvious isn't okay.

编辑:哇,我想省略显而易见的事情是不行的。

lines = bigstring.split()
lines = [line for line in lines if line.strip()]

回答by Regisz

I also tried regexp and list solutions, and list one is faster.

我还尝试了 regexp 和 list 解决方案,并且list one is fast

Here is my solution (by previous answers):

这是我的解决方案(根据以前的答案):

text = "\n".join([ll.rstrip() for ll in original_text.splitlines() if ll.strip()])

回答by Ooker

If you are not willing to try regex (which you should), you can use this:

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

s.replace('\n\n','\n')

Repeat this several times to make sure there is no blank line left. Or chaining the commands:

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

s.replace('\n\n','\n').replace('\n\n','\n')



Just to encourage you to use regex, here are two introductory videos that I find intuitive:
? Regular Expressions (Regex) Tutorial
? Python Tutorial: re Module

只是为了鼓励您使用正则表达式,这里有两个介绍影片,我觉得直观的:
正则表达式(Regex)教程
Python 教程:re 模块

回答by Radren

My version:

我的版本:

while '' in all_lines:
    all_lines.pop(all_lines.index(''))

回答by Radren

while True:
    try:
        all_lines.remove('')
    except ValueError:
        break

回答by Kashem Ali

komodo edit remove blank lines

科莫多编辑删除空行

In komodo edit press Ctrl+H Star Mark (Treat as regex), Click above link to view snapshot.

在 komodo 编辑中按 Ctrl+H 星标(视为正则表达式),单击上面的链接查看快照。

回答by Reihan_amn

Same as what @NullUserException said, this is how I write it:

与@NullUserException 所说的相同,我是这样写的:

removedWhitespce = re.sub(r'^\s*$', '', line)

回答by mushuweasel

Surprised a multiline re.sub has not been suggested (Oh, because you've already split your string... But why?):

惊讶的是没有建议多行 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

>>>