remove all elements in a list with a particular value

Lisa lisa.engblom at gmail.com
Wed May 16 11:21:13 EDT 2007


I am reading in data from a text file.  I want to enter each value on
the line into a list and retain the order of the elements.  The number
of elements and spacing between them varies, but a typical line looks
like:

'   SRCPARAM   1 6.35e-07 15.00  340.00   1.10      3.0   '

Why does the following not work:

line = '   SRCPARAM   1 6.35e-07 15.00  340.00   1.10      3.0   '
li = line.split(' ')
for j,i in enumerate(li):
	if i == '':
		li.remove(i)

After the original split I get:
['', '', '', 'SRCPARAM', '', '', '1', '6.35e-07', '15.00', '',
'340.00', '', '', '1.10', '', '', '', '', '', '3.0', '', '', '']

And after the for loop I get:
['SRCPARAM', '1', '6.35e-07', '15.00', '340.00', '1.10', '', '', '',
'3.0', '', '', '']

It doesn't remove all of the empty elements.  Is there a better way to
split the original string?  Or a way to catch all of the empty
elements?

Thanks




More information about the Python-list mailing list