用一句简短代码怎么去掉Python字符串中的空行?

89 投票
13 回答
117447 浏览
提问于 2025-04-15 12:57

我有一段Python代码,它是以字符串的形式存在的,但里面有很多多余的空行。我想把这些空行都去掉。请问用Python最简单的方法是什么?

注意:我不是在找一个通用的代码格式化工具,只想要一个简单的一两行代码。

谢谢!

13 个回答

20

关于去除换行符和空行的课程

这里的 "t" 是一个包含文本的变量。你会看到一个 "s" 变量,它是一个临时变量,只在处理主要的括号内容时存在(我忘了这些小括号在 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
""""

这是我们在不使用 "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' 

要看到实际的换行,记得打印出来。

>>> 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().splitlines(True) 中的 strip 可以去掉,这样就变成 t.splitlines(True),但这样输出可能会多出一个换行(所以它去掉了最后的换行)。最后部分的 s.strip("\r\n").strip() 和 s.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?

** 关于中间的 strip 的说明 **

这个中间的 strip 附加在 "t" 变量上,只是去掉最后一个换行(正如之前的说明所说)。这是没有这个 strip 时的样子(注意最后的换行):

第一个例子(去掉换行和带空格的换行):

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

结束!

25
"\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() 就可以解决了。

124

这样怎么样:

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

这里的 text 是可能包含多余行的字符串吗?

撰写回答