How to convert a string into a list

Chris Rebert clp2 at rebertia.com
Mon Oct 4 21:29:43 EDT 2010


On Mon, Oct 4, 2010 at 6:25 PM, James Mills
<prologic at shortcircuit.net.au> 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?

> If you trust the source of the data

Um, he specifically said:
>> I don't want to use eval, as the
>> string is coming from an untrusted source.

> the following
> is probably the simplest:
>
>>>> s = "['1', '2']"
>>>> [int(x) for x in eval(s)]
> [1, 2]

Cheers,
Chris



More information about the Python-list mailing list