String To List

Tom Stambaugh tms at zeetix.com
Mon Mar 17 08:01:59 EDT 2008


It's too bad your inner data items are delimited with an apostrophe (') 
instead a double-quote ("). If they were double-quote, you could do 
something as simple as:

Given:
a = '["xyz", "abc"]'

import simplejson
answer = simplejson.loads(a)

There may be an incantation to simplejson that allows you to use a different 
delimiter. You might be able to provide your own decoder, using the "cls=" 
argument (but I don't think that lets you change the delimiter string). 
Failing that, and depending on your regex/Python prowess, you might be able 
to change the "decoder.py" file within simplejson to do what you want.

As others have observed, a lot depends on the input data. If it really is as 
simple as your example, then the following may do the trick:

a = "['xyz', 'abc']"

answer = map(lambda each: each.strip()[1:-1], a[1:-1].split(','))

This at least has no "eval", and so you need not fear applying it to unknown 
data (it will just break).

The answer that works best for you may perhaps be somewhere in the middle.

"Girish" <girish.cfc at gmail.com> wrote in message 
news:e6035b85-d00c-4a35-951d-8287a99f7d8b at s8g2000prg.googlegroups.com...
>I have a string a = "['xyz', 'abc']".. I would like to convert it to a
> list with elements 'xyz' and 'abc'. Is there any simple solution for
> this??
> Thanks for the help...
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 






More information about the Python-list mailing list