How to remove empty lines with or without whitespace in Python

Viewed 194531

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
12 Answers

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

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

>>> 

you can simply use rstrip:

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

I use this solution to delete empty lines and join everything together as one line:

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

Use positive lookbehind regex:

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

When you input:

foo
<tab> <tab>

bar

The output will be:

foo
bar
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)

Output:

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