Splitting lines in a file

Chris Liechti cliechti at gmx.net
Sun Jul 7 18:07:47 EDT 2002


simon at uggs.demon.co.uk (Simon Foster) wrote in 
news:3d28b895.70324260 at news.dsl.pipex.com:
> How come when I split a file on arbitrary whitespace I get one fewer
> lines then when I split on end of line?  In the case when I split on
> the \n the last line has zero length.

'cause split() drops the empty part at the end:
>>> '1\n2\n3\n'.split()
['1', '2', '3']
>>> '1\n2\n3\n'.split('\n')
['1', '2', '3', '']

split() works on different whitespace characters at the same time and 
removes them more agressively (see below). when you specify a split 
character like split('\n') only that character matters.

split() is more agressive in removing empty parts (note the two spaces 
between a and b):
>>> 'a  b'.split()
['a', 'b']
>>> 'a  b'.split(' ')
['a', '', 'b']

chris

-- 
Chris <cliechti at gmx.net>




More information about the Python-list mailing list