String To List
tms at zeetix.com
Mon Mar 17 13:01:59 CET 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:
a = '["xyz", "abc"]'
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
> Thanks for the help...
More information about the Python-list