从 python 字符串中删除空行的快速单行是什么?

发布于 2024-07-27 04:11:13 字数 133 浏览 6 评论 0原文

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

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

谢谢!

I have some code in a python string that contains extraneous empty lines. I would like to remove all empty lines from the string. What's the most pythonic way to do this?

Note: I'm not looking for a general code re-formatter, just a quick one or two-liner.

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

盗梦空间 2024-08-03 04:11:13

怎么样:

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

其中 text 是带有可能无关行的字符串?

How about:

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

where text is the string with the possible extraneous lines?

高跟鞋的旋律 2024-08-03 04:11:13
"\n".join([s for s in code.split("\n") if s])

Edit2:

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

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

"\n".join([s for s in code.split("\n") if s])

Edit2:

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

I think that's my final version. It should work well even with code mixing line endings. I don't think that line with spaces should be considered empty, but if so then simple s.strip() will do instead.

老旧海报 2024-08-03 04:11:13

关于删除换行符和带空格的空行的课程

“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).

结束!

LESSON ON REMOVING NEWLINES and EMPTY LINES WITH SPACES

"t" is the variable with the text. You will see an "s" variable, its a temporary variable that only exists during the evaluation of the main set of parenthesis (forgot the name of these lil python things)

First lets set the "t" variable so it has new lines:

>>> 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'

Note there is another way to set the varible using triple quotes

somevar="""
   asdfas
asdf

  asdf

  asdf

asdf
""""

Here is how it looks when we view it without "print":

>>> 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' 

To see with actual newlines, print it.

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

of empty
line
even some with spaces

like that


okay now what?

COMMAND REMOVE ALL BLANK LINES (INCLUDING SPACES):

So somelines newlines are just newlines, and some have spaces so they look like new lines

If you want to get rid of all blank looking lines (if they have just newlines, or spaces as well)

>>> 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?

OR:

>>> 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?

NOTE: that strip in t.strip().splitline(True) can be removes so its just t.splitlines(True), but then your output can end with an extra newline (so that removes the final newline). The strip() in the last part s.strip("\r\n").strip() and s.strip() is what actually removes the spaces in newlines and newlines.

COMMAND REMOVE ALL BLANK LINES (BUT NOT ONES WITH SPACES):

Technically lines with spaces should NOT be considered empty, but it all depends on the use case and what your trying to achieve.

>>> 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?

** NOTE ABOUT THAT MIDDLE strip **

That middle strip there, thats attached to the "t" variable, just removes the last newline (just as the previous note has stated). Here is how it would look like without that strip being there (notice that last newline)

With 1st example (removing newlines and newlines with spaces)

>>> 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).

With 2nd example (removing newlines only)

>>> 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).

The END!

心舞飞扬 2024-08-03 04:11:13
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()]

并且可能对可读性有用

filter(None, code.splitlines())
filter(str.strip, code.splitlines())

are equivalent to

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

and might be useful for readability

深海里的那抹蓝 2024-08-03 04:11:13

通过使用 re.sub 函数

re.sub(r'^$\n', '', s, flags=re.MULTILINE)

By using re.sub function

re.sub(r'^$\n', '', s, flags=re.MULTILINE)
月光色 2024-08-03 04:11:13

这是一个单行解决方案:

print("".join([s for s in mystr.splitlines(True) if s.strip()]))

Here is a one line solution:

print("".join([s for s in mystr.splitlines(True) if s.strip()]))
夏日落 2024-08-03 04:11:13

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

import re    
re.sub(r'\n\s*\n', '\n', text, flags=re.MULTILINE)

This code removes empty lines (with or without whitespaces).

import re    
re.sub(r'\n\s*\n', '\n', text, flags=re.MULTILINE)
月棠 2024-08-03 04:11:13

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

str(textWithEmptyLines).replace('\n\n','')

IMHO shortest and most Pythonic would be:

str(textWithEmptyLines).replace('\n\n','')
叫思念不要吵 2024-08-03 04:11:13

这也会删除空格行。

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

This one will remove lines of spaces too.

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

屋顶上的小猫咪 2024-08-03 04:11:13

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

using regex
re.sub(r'^$\n', '', somestring, flags=re.MULTILINE)

我早已燃尽 2024-08-03 04:11:13

现在来说一些完全不同的东西:

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)

And now for something completely different:

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'

Episode 2:

This one doesn't work on 1.5 :-(

BUT not only does it handle universal newlines and blank lines, it also removes trailing whitespace (good idea when tidying up code lines IMHO) AND does a repair job if the last meaningful line is not terminated.

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)
月棠 2024-08-03 04:11:13

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

"".join(filter(str.strip, sample_string.splitlines(True)))

expanding on ymv's answer, you can use filter with join to get desired string,

"".join(filter(str.strip, sample_string.splitlines(True)))
我偏爱纯白色 2024-08-03 04:11:13

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

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

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

print("    \n"

I wanted to remove a bunch of empty lines and what worked for me was:

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

I went with 2 since that covered the \r\n.
I did want a few empty rows just to make my formatting look better so in those cases I had to use:

print("    \n"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文