How to convert a string into a list

Steven D'Aprano steve-REMOVE-THIS at cybersource.com.au
Mon Oct 4 22:11:01 EDT 2010


On Tue, 05 Oct 2010 11:25:58 +1000, James Mills wrote:

> On Tue, Oct 5, 2010 at 11:10 AM, Mark Phillips
> <mark at phillipsmarketing.biz> wrote:
>> I have the following string - "['1', '2']" that I need to convert into
>> a list of integers - [1,2]. The string can contain from 1 to many
>> integers. Eg "['1', '7', '4',......,'n']" (values are not sequential)
>>
>> What would be the best way to do this? I don't want to use eval, as the
>> string is coming from an untrusted source.
> 
> If you trust the source of the data the following is probably the
> simplest:
> 
>>>> s = "['1', '2']"
>>>> [int(x) for x in eval(s)]
> [1, 2]

You fail at reading comprehension :) Perhaps you missed your coffee this 
morning?



The Effbot has a nice little recipe for safely parsing strings as Python 
objects:

http://effbot.org/zone/simple-iterator-parser.htm

This is probably overkill for the specific task. Depending on how 
forgiving you want to be of syntax, this may be simple enough:

>>> s = "[ '1' , \"2\" , '3', ' 4 ', 5 ]"
>>> s = s.replace("'", "").replace('"', "")
>>> s = s.strip().strip('[]').replace(',', ' ')
>>> [int(i) for i in s.split()]
[1, 2, 3, 4, 5]


If you don't need to enforce a specific syntax, don't bother, just chop 
off the rubbish you don't need with strip() and replace().




-- 
Steven



More information about the Python-list mailing list