[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.python

String To List

Girish

3/17/2008 6:16:00 AM

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...
4 Answers

Dan Bishop

3/17/2008 6:57:00 AM

0

On Mar 17, 1:15 am, Girish <girish....@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(', ')]

Paul Rubin

3/17/2008 8:22:00 AM

0

Girish <girish.cfc@gmail.com> writes:
> 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...

Be careful about using eval, if the string came from a potentially
hostile source. Maybe what you really want is JSON, which has
python-like syntax but a bunch of safe parsers.

Iain King

3/17/2008 9:28:00 AM

0

On Mar 17, 6:56 am, Dan Bishop <danb...@yahoo.com> wrote:
> On Mar 17, 1:15 am, Girish <girish....@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

George Sakkis

3/17/2008 9:59:00 AM

0

On Mar 17, 3:22 am, Paul Rubin <http://phr...@NOSPAM.invalid> wrote:
> Girish <girish....@gmail.com> writes:
> > 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...
>
> Be careful about using eval, if the string came from a potentially
> hostile source. Maybe what you really want is JSON, which has
> python-like syntax but a bunch of safe parsers.

Or take a look at a restricted safe eval variant (e.g.
http://groups.google.com/group/comp.lang.python/browse_frm/thread/262d47...)

George