Re: How to convert a string into a list
- From: Chris Rebert <clp2@xxxxxxxxxxxx>
- Date: Mon, 4 Oct 2010 23:54:49 -0700
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 aI'd probably use a regex, although others might think it's overkill. :-)
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.
[1, 2]import re
s = "['1', '2']"
[int(n) for n in re.findall(r'-?\d+', s)]
An alternative is:
[1, 2]s = "['1', '2']"
[int(n.strip("'[] ")) for n in s.split(",")]
I'll add:
[1, 2, 42]s = ['1', '2', '42']
[int(x) for x in s.split("'")[1::2]]
There's also:
[1, 2]s = "['1', '2']"
from ast import literal_eval
[int(n) for n in literal_eval(s)]
Which is safe, but less strict.
Cheers,
Chris
--
http://blog.rebertia.com
.
- References:
- Re: How to convert a string into a list
- From: MRAB
- Re: How to convert a string into a list
- From: Arnaud Delobelle
- Re: How to convert a string into a list
- Prev by Date: Re: Problem installing psycopg2 in virtualenv (Ubuntu 10.04, Python 2.5)
- Next by Date: Re: Help with sets
- Previous by thread: Re: How to convert a string into a list
- Next by thread: Help with sets
- Index(es):
Relevant Pages
|