78

我在 python 字符串中有一些代码,其中包含无关的空行。我想从字符串中删除所有空行。最pythonic的方法是什么?

注意:我不是在寻找通用的代码重新格式化程序,只是快速的一两行代码。

谢谢!

4

13 回答 13

111

怎么样:

text = os.linesep.join([s for s in text.splitlines() if s])

text可能有多余行的字符串在哪里?

于 2009-07-17T00:25:15.777 回答
22
"\n".join([s for s in code.split("\n") if s])

编辑2:

text = "".join([s for s in code.splitlines(True) if s.strip("\r\n")])

我认为这是我的最终版本。即使使用代码混合行结尾,它也应该能很好地工作。我不认为带空格的行应该被认为是空的,但如果是这样,那么简单的 s.strip() 会代替。

于 2009-07-17T00:25:18.257 回答
18

使用空格删除换行符和空行的课程

“t”是带有文本的变量。您将看到一个“s”变量,它是一个临时变量,仅在评估主括号集期间存在(忘记了这些 lil python 事物的名称)

首先让我们设置“t”变量,使其具有新行:

>>> t='hi there here is\na big line\n\nof empty\nline\neven some with spaces\n       \nlike that\n\n    \nokay now what?\n'

请注意,还有另一种使用三引号设置变量的方法

somevar="""
   asdfas
asdf

  asdf

  asdf

asdf
""""

这是我们在没有“打印”的情况下查看它时的样子:

>>> t
'hi there here is\na big line\n\nof empty\nline\neven some with spaces\n       \nlike that\n\n    \nokay now what?\n' 

要查看实际的换行符,请打印它。

>>> print t
hi there here is
a big line

of empty
line
even some with spaces

like that


okay now what?

命令删除所有空白行(包括空格):

所以有些行换行符只是换行符,有些有空格,所以它们看起来像新行

如果您想摆脱所有看起来空白的行(如果它们只有换行符或空格)

>>> print "".join([s for s in t.strip().splitlines(True) if s.strip()])
hi there here is
a big line
of empty
line
even some with spaces
like that
okay now what?

或者:

>>> print "".join([s for s in t.strip().splitlines(True) if s.strip("\r\n").strip()])
hi there here is
a big line
of empty
line
even some with spaces
like that
okay now what?

注意:可以删除 t.strip().splitline(True) 中的条带,因此它只是 t.splitlines(True),但是您的输出可以以额外的换行符结尾(这样会删除最后的换行符)。最后一部分 s.strip("\r\n").strip() 和 s.strip() 中的 strip() 实际上是删除换行符和换行符中的空格。

命令删除所有空白行(但不是带空格的):

从技术上讲,带空格的行不应被视为空行,但这完全取决于用例和您要实现的目标。

>>> print "".join([s for s in t.strip().splitlines(True) if s.strip("\r\n")])
hi there here is
a big line
of empty
line
even some with spaces

like that

okay now what?

**关于中间条的注意事项**

那里的中间条,附加到“t”变量,只是删除最后一个换行符(正如前面的注释所说)。这是没有那个条的情况下的样子(注意最后一个换行符)

使用第一个示例(删除换行符和带空格的换行符)

>>> print "".join([s for s in t.strip().splitlines(True) if s.strip("\r\n").strip()])
hi there here is
a big line
of empty
line
even some with spaces
like that
okay now what?
.without strip new line here (stackoverflow cant have me format it in).

使用第二个示例(仅删除换行符)

>>> print "".join([s for s in t.strip().splitlines(True) if s.strip("\r\n")])
hi there here is
a big line
of empty
line
even some with spaces

like that

okay now what?
.without strip new line here (stackoverflow cant have me format it in).

结束!

于 2014-06-11T21:16:55.100 回答
14
filter(None, code.splitlines())
filter(str.strip, code.splitlines())

相当于

[s for s in code.splitlines() if s]
[s for s in code.splitlines() if s.strip()]

并且可能对可读性有用

于 2009-07-17T07:46:23.640 回答
8

通过使用re.sub函数

re.sub(r'^$\n', '', s, flags=re.MULTILINE)
于 2017-12-20T04:46:11.677 回答
4

这是一个单行解决方案:

print("".join([s for s in mystr.splitlines(True) if s.strip()]))
于 2017-09-26T00:44:34.577 回答
3

此代码删除空行(带或不带空格)。

import re    
re.sub(r'\n\s*\n', '\n', text, flags=re.MULTILINE)
于 2019-07-01T10:35:27.233 回答
3

恕我直言,最短和最 Pythonic 将是:

str(textWithEmptyLines).replace('\n\n','')
于 2020-01-05T18:34:11.923 回答
1

这也将删除空格行。

re.replace(u'(?imu)^\s*\n', u'', code)

于 2009-07-17T01:15:55.617 回答
1

使用正则表达式 re.sub(r'^$\n', '', somestring, flags=re.MULTILINE)

于 2021-06-15T20:45:51.603 回答
0

现在来点完全不同的东西:

Python 1.5.2 (#0, Apr 13 1999, 10:51:12) [MSC 32 bit (Intel)] on win32
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> import string, re
>>> tidy = lambda s: string.join(filter(string.strip, re.split(r'[\r\n]+', s)), '\n')
>>> tidy('\r\n   \n\ra\n\n   b   \r\rc\n\n')
'a\012   b   \012c'

第 2 集:

这个不适用于 1.5 :-(

但它不仅处理通用换行符和空白行,它还删除尾随空格(整理代码行时好主意恕我直言)并且如果最后一个有意义的行没有终止,则进行修复工作。

import re
tidy = lambda c: re.sub(
    r'(^\s*[\r\n]+|^\s*\Z)|(\s*\Z|\s*[\r\n]+)',
    lambda m: '\n' if m.lastindex == 2 else '',
    c)
于 2009-07-17T12:24:59.567 回答
0

扩展 ymv 的答案,您可以使用filterwithjoin来获取所需的字符串,

"".join(filter(str.strip, sample_string.splitlines(True)))
于 2019-01-02T03:54:11.787 回答
0

我想删除一堆空行,对我有用的是:

if len(line) > 2:
    myfile.write(output)

我选择了 2,因为它涵盖了 \r\n。我确实想要一些空行只是为了让我的格式看起来更好,所以在这些情况下我不得不使用:

print("    \n"
于 2019-08-02T18:06:15.500 回答