Remove empty strings from list

tec technic.tec at gmail.com
Mon Sep 14 22:38:42 EDT 2009


Helvin 写道:
> Hi,
> 
> Sorry I did not want to bother the group, but I really do not
> understand this seeming trivial problem.
> I am reading from a textfile, where each line has 2 values, with
> spaces before and between the values.
> I would like to read in these values, but of course, I don't want the
> whitespaces between them.
> I have looked at documentation, and how strings and lists work, but I
> cannot understand the behaviour of the following:
>                         line = f.readline()
> 			line = line.lstrip() # take away whitespace at the beginning of the
> readline.
> 			list = line.split(' ') # split the str line into a list
> 
>                         # the list has empty strings in it, so now,
> remove these empty strings
> 			for item in list:
> 				if item is ' ':
> 					print 'discard these: ',item
> 					index = list.index(item)
> 					del list[index]         # remove this item from the list
> 				else:
> 					print 'keep this: ',item
> The problem is, when my list is :  ['44', '', '', '', '', '',
> '0.000000000\n']
> The output is:
>     len of list:  7
>     keep this:  44
>     discard these:
>     discard these:
>     discard these:
> So finally the list is:   ['44', '', '', '0.000000000\n']
> The code above removes all the empty strings in the middle, all except
> two. My code seems to miss two of the empty strings.
> 
> Would you know why this is occuring?
> 
> Regards,
> Helvin

You can use the default argument of split:
list = line.split()

 From the python documentation,

"If the optional second argument sep is absent or None, the words are 
separated by arbitrary strings of whitespace characters (space, tab, 
newline, return, formfeed)."

So it is suitable for most cases without introduce empty strings.



More information about the Python-list mailing list