Thanks to everyone for their suggestions. I learned a lot from them!<br><br>Mark<br><br><div class="gmail_quote">On Mon, Oct 4, 2010 at 11:54 PM, Chris Rebert <span dir="ltr"><<a href="mailto:clp2@rebertia.com">clp2@rebertia.com</a>></span> wrote:<br>
<blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;"><div><div></div><div class="h5">On Mon, Oct 4, 2010 at 10:33 PM, Arnaud Delobelle <<a href="mailto:arnodel@gmail.com">arnodel@gmail.com</a>> wrote:<br>

> MRAB <<a href="mailto:python@mrabarnett.plus.com">python@mrabarnett.plus.com</a>> writes:<br>
>> On 05/10/2010 02:10, Mark Phillips wrote:<br>
>>> I have the following string - "['1', '2']" that I need to convert into a<br>
>>> list of integers - [1,2]. The string can contain from 1 to many<br>
>>> integers. Eg "['1', '7', '4',......,'n']" (values are not sequential)<br>
>>><br>
>>> What would be the best way to do this? I don't want to use eval, as the<br>
>>> string is coming from an untrusted source.<br>
>>><br>
>> I'd probably use a regex, although others might think it's overkill. :-)<br>
>><br>
>>>>> import re<br>
>>>>> s = "['1', '2']"<br>
>>>>> [int(n) for n in re.findall(r'-?\d+', s)]<br>
>> [1, 2]<br>
>><br>
>> An alternative is:<br>
>><br>
>>>>> s = "['1', '2']"<br>
>>>>> [int(n.strip("'[] ")) for n in s.split(",")]<br>
>> [1, 2]<br>
><br>
> I'll add:<br>
><br>
>>>> s = ['1', '2', '42']<br>
>>>> [int(x) for x in s.split("'")[1::2]]<br>
> [1, 2, 42]<br>
<br>
</div></div>There's also:<br>
>>> s = "['1', '2']"<br>
>>> from ast import literal_eval<br>
>>> [int(n) for n in literal_eval(s)]<br>
[1, 2]<br>
<br>
Which is safe, but less strict.<br>
<div class="im"><br>
Cheers,<br>
Chris<br>
--<br>
<a href="http://blog.rebertia.com" target="_blank">http://blog.rebertia.com</a><br>
</div><div><div></div><div class="h5">--<br>
<a href="http://mail.python.org/mailman/listinfo/python-list" target="_blank">http://mail.python.org/mailman/listinfo/python-list</a><br>
</div></div></blockquote></div><br>