How to convert a string into a list

Arnaud Delobelle arnodel at gmail.com
Tue Oct 5 01:33:09 EDT 2010


MRAB <python at mrabarnett.plus.com> writes:

> On 05/10/2010 02:10, Mark Phillips 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.
>>
> I'd probably use a regex, although others might think it's overkill. :-)
>
>>>> import re
>>>> s = "['1', '2']"
>>>> [int(n) for n in re.findall(r'-?\d+', s)]
> [1, 2]
>
> An alternative is:
>
>>>> s = "['1', '2']"
>>>> [int(n.strip("'[] ")) for n in s.split(",")]
> [1, 2]

I'll add:

>>> s = ['1', '2', '42']
>>> [int(x) for x in s.split("'")[1::2]]
[1, 2, 42]

-- 
Arnaud



More information about the Python-list mailing list