views:

96

answers:

3
+2  Q: 

Remove empty lines

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
+3  A: 

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.

NullUserException
Thanks for all the results, however, this solution was exactly what I had been looking for! Thanks a lot
+8  A: 

Try list comprehension and 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']
gimel
+1 for helpfully showing intermediate result.
LarsH
+1 This is pretty much exactly how I solved this problem when I had it.
kindall
+3  A: 

Edit: Wow, I guess omitting the obvious isn't okay.

lines = bigstring.split()
lines = [line for line in lines if line.strip()]
Nathon
That would work for lines = ['Line\n', '\n', 'Line\n'] but the input is 'Line\n\nLine\n' .
Walter Nissen
@Walter: Actually, if you used 'Line\n\nLine\n'.split() like you should have, it would work just fine.
Nathon