Remove empty lines

Sheila King usenet at thinkspot.net
Wed Mar 20 14:21:43 EST 2002


On Wed, 20 Mar 2002 10:33:55 -0800, "Nick Arnett" <narnett at mccmedia.com>
wrote in comp.lang.python in article
<mailman.1016649277.6397.python-list at python.org>:

> The problem is here, I think.  Split in Python appears to return the
> separator, so the '\n' characters are still there.  If that's the problem,
> this should fix it.
> 
> if line == '\n':
> 
> At least, that's my suspicion, without testing.  (In Perl, the separators
> are not returned by default, so if you came to Python from Perl, like me,
> this is confusing.)

Here is what happens:

Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
IDLE 0.8 -- press F1 for help
>>> mystring = 'Hello.\n\nHow are you today?\nFine, thanks.\n\n\nSee ya!'
>>> mylist = mystring.split('\n')
>>> mylist
['Hello.', '', 'How are you today?', 'Fine, thanks.', '', '', 'See ya!']
>>> mylist = filter(None, mylist)
>>> mylist
['Hello.', 'How are you today?', 'Fine, thanks.', 'See ya!']
>>> 

It doesn't return the separator, however, it does return empty strings
between consecutive occurrences of the separator.

One option for removing them, is the filter function.

Or, you could use list comprehensions:

>>> 
>>> mystring
'Hello.\n\nHow are you today?\nFine, thanks.\n\n\nSee ya!'
>>> mystring.split('\n')
['Hello.', '', 'How are you today?', 'Fine, thanks.', '', '', 'See ya!']
>>> mylist = [part for part in mystring.split('\n') if part]
>>> mylist
['Hello.', 'How are you today?', 'Fine, thanks.', 'See ya!']
>>> 

--
Sheila King
http://www.thinkspot.net/sheila/
http://www.k12groups.org/




More information about the Python-list mailing list