STRING TO LIST

Duncan Booth duncan at NOSPAMrcp.co.uk
Wed Apr 9 04:48:47 EDT 2003


"Terry Reedy" <tjreedy at udel.edu> wrote in 
news:sNicneNGn5EZ6g6jXTWcpQ at comcast.com:

>> I need to change a variable from string to list.
>> > >>> x=str("[[12,13],[14,15]]")
>> > must be a list like this:
>> > [[12, 13], [14, 15]]
> 
>>>> eval('[[12,13],[14,15]]' )
> [[12, 13], [14, 15]]
> 

While this works, the original poster should be aware that unless he/she 
has full control over the origin of the string, it could have nasty side 
effects, since the string could do things like opening files or even 
executing arbitrary Python code.

Of course this may not be relevant, but in case it is, a better solution 
is:

>>> x=str("[[12,13],[14,15]]")
>>> print eval(x, {'__builtins__': {}})
[[12, 13], [14, 15]]
>>> 

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?




More information about the Python-list mailing list