String To List

Iain King iainking at gmail.com
Mon Mar 17 10:27:31 CET 2008


On Mar 17, 6:56 am, Dan Bishop <danb... at yahoo.com> wrote:
> On Mar 17, 1:15 am, Girish <girish.... at gmail.com> wrote:
>
> > 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...
>
> eval(a) will do the job, but you have to be very careful about using
> that function.  An alternative is
>
> [s.strip('\'"') for s in a.strip('[]').split(', ')]

This will fall over if xyz or abc include any of the characters your
stripping/splitting on (e.g if xyz is actually "To be or not to be,
that is the question").  Unless you can guarantee they won't, you'll
need to write (or rather use) a parser that understands the syntax.

Iain



More information about the Python-list mailing list