string to list when the contents is a list

Rhodri James rhodri at wildebst.demon.co.uk
Thu Feb 18 19:26:59 EST 2010


On Thu, 18 Feb 2010 14:52:29 -0000, nn <pruebauno at latinmail.com> wrote:

> Wes James wrote:
>> I have been trying to create a list form a string.  The string will be
>> a list (this is the contents will look like a list).  i.e. "[]" or
>> "['a','b']"
>>
>> The "[]" is simple since I can just check if value == "[]" then return  
>> []
>>
>> But with "['a','b']" I have tried and get:
>>
>> a="['a','b']"
>>
>> b=a[1:-1].split(',')
>>
>> returns
>>
>> [ " 'a' "," 'b' " ]
>>
>> when I want it to return ['a','b'].
>>
>> How can I do this?
>>
>> thx,
>>
>> -wes
>
>
> I am surprised nobody gave you the simple answer yet that may even
> work for your situation:
>
> b=a[2:-2].split("','")

Because it's really *very* not robust.  "Harmless" whitespace defeats it  
for starters, and that's one of the most likely things to vary between  
example data and reality.  If you trust your data to be well-formed enough  
for this to work, you might as well use eval() instead.  If you don't,  
parsing is the only sensible answer.

-- 
Rhodri James *-* Wildebeeste Herder to the Masses



More information about the Python-list mailing list