如何删除带或不带空格的空行

问题描述 投票:0回答:14

我有一个很大的字符串,我用换行符分割了它。 如何删除所有空行(仅限空白)?

伪代码:

for stuff in largestring:
   remove stuff that is blank
python string whitespace
14个回答
72
投票

尝试列表理解和

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

52
投票

使用正则表达式:

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

使用正则表达式+

filter()
:

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

键盘上所示。


27
投票

我还尝试了正则表达式和列表解决方案,并且列出一个更快

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

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

13
投票
lines = bigstring.split('\n')
lines = [line for line in lines if line.strip()]

8
投票

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

>>> 

3
投票

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

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

重复此操作数次,以确保没有空白行。或者链接命令:

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


为了鼓励您使用正则表达式,这里有两个我认为直观的介绍性视频:
正则表达式 (Regex) 教程
Python 教程:重新模块


2
投票

您可以简单地使用 rstrip:

    for stuff in largestring:
        print(stuff.rstrip("\n")

1
投票

我使用此解决方案删除空行并将所有内容连接在一起作为一行:

match_p = re.sub(r'\s{2}', '', my_txt) # my_txt is text above

0
投票

我的版本:

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

0
投票

使用正向lookbehind正则表达式:

re.sub(r'(?<=\n)\s+', '', s, re.MULTILINE)

当您输入:

foo
<tab> <tab>

bar

输出将是:

foo
bar

0
投票
str_whith_space = """
    example line 1

    example line 2
    example line 3

    example line 4"""

new_str = '\n'.join(el.strip() for el in str_whith_space.split('\n') if el.strip())
print(new_str)

输出:

""" <br>
example line 1 <br>
example line 2 <br>
example line 3 <br>
example line 4 <br>
"""

0
投票

您可以组合

map
strip
来删除空格并使用
filter(None, iterable)
来删除空元素:

string = "a\n \n\nb"
list_of_str = string.split("\n")
list_of_str = filter(None, map(str.strip, list_of_str))
list(list_of_str)

退货:

['a', 'b']


0
投票
 html_content = [l for l in html_content.splitlines() if l.rstrip()]
 html_content = "\n".join(html_content)

-1
投票

和@NullUserException说的一样,我是这样写的:

removedWhitespce = re.sub(r'^\s*$', '', line)
© www.soinside.com 2019 - 2024. All rights reserved.