Lisa wrote: > 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 >
When you split on a space (' ') multiple spaces will return empty list elements between them. Change to: line = ' SRCPARAM 1 6.35e-07 15.00 340.00 1.10 3.0 ' li = line.split() And you will get what you want: ['SRCPARAM', '1', '6.35e-07', '15.00', '340.00', '1.10', '3.0'] -Larry -- http://mail.python.org/mailman/listinfo/python-list