user428370 user428370 - 1 year ago 128
Python Question

How to remove empty lines with or without whitespace in Python

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

Answer Source

Using regex:

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

Using regex + filter():

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

As seen on codepad.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download