creating a subnested lists from a comma seperated string read from a file

Russell Blau russblau at
Thu Aug 22 21:37:38 CEST 2002

"Danathar" <dougb at> wrote in message
news:2f177cd8.0208221108.1dbdb6b4 at
> How can I take each string element in my LIST variable with my comma
> seperated fields and turn them into a subnested lists with each comma
> seperated field as individual elements....
> example...
> How do I turn List variable called "test"
> test = 'john, bill, 1234, 4.5' , 'mary, bob, 4567, 9.2'

That's not a list:  A list is demarcated by [ brackets ]; a string is
demarcated by ' quotes ' (or " quotes " or ...); if you actually entered
the line above, you'd get a tuple containing two strings.

I think you want

test = ['john, bill, 1234, 4.5', 'mary, bob, 4567, 9.2']

> into
> test = '['john', 'bill', 1234, 4.5], ['mary', 'bob', 4567, 9.2]'

I think you want

test = [['john', 'bill', 1234, 4.5], ['mary', 'bob', 4567, 9.2]]

> I could sove the problem with a while or do conditional and step
> through each of the original elemnts, look for commas, split them and
> then re-assign them, but that seems like alot of work, is there a
> better way?

Why, yes there is!  Try:

    test = [line.split(',') for line in test]

Now, that will not produce exactly the same result you wanted, because
it will not convert the numeric strings to integers or floats.  That
process is a little more complicated, but basically you could do
something like this:

    for line in test:
        for x in range(len(line)):
                line[x] = int(line[x])
                    line[x] = float(line[x])

[You need to try the "int" conversion first, or else Python will happily
convert "17" into the floating point value 17.0]

I'm virtually certain that someone else will come up with a better way
to do the conversion step!  ;-)

I don't actually have a hotmail account; but I do have one on
if you really want to get in touch with me.

More information about the Python-list mailing list