# Re: How to convert a string into a list

On Mon, Oct 4, 2010 at 10:33 PM, Arnaud Delobelle <arnodel@xxxxxxxxx> wrote:
MRAB <python@xxxxxxxxxxxxxxxxxxx> 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]

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

There's also:
s = "['1', '2']"
from ast import literal_eval
[int(n) for n in literal_eval(s)]
[1, 2]

Which is safe, but less strict.

Cheers,
Chris
--
http://blog.rebertia.com
.

## Relevant Pages

• Re: 0 == false == ""
... This makes no sense as a typeof operation evaluates to a string ... If you used a loose comparison on an empty string, ... programmer is simply saying "compare these things in a strict manner," ...
(comp.lang.javascript)
• Re: error printing page using LWP::Simple
... # use strict; ... # perl scraper2.pl ... Use of uninitialized value in concatenation or string at scraper3.pl ...
(comp.lang.perl.misc)
• Re: Filehandles Referenced with a Variable
... >> it's a reference to a filehandle, when it's a string, naturally it ... read perldoc perldata for that. ... MF> with 'use strict' commented out, ... MF> wraps when other e-mail lists don't. ...
(comp.lang.perl.misc)
• Re: use strict and s///ee
... > last PATTERN; ... > translate as I expect. ... > If I remove use strict, then translation works as I want. ... You use a bareword string in the expression ...
(comp.lang.perl.misc)
• Re: Appending variables
... Is it a reference to an array? ... Then it returns the string. ... And more importantly, why are you not using strict, ... claimed, then you have a variable \$config, and trying to access ...
(perl.beginners)