how to convert string to list or tuple
Fredrik Lundh
fredrik at pythonware.com
Thu May 26 08:11:47 EDT 2005
"flyaflya" <flyaflya at gmail.com> wrote:
>a = "(1,2,3)"
> I want convert a to tuple:(1,2,3),but tuple(a) return ('(', '1', ',',
> '2', ',', '3', ')') not (1,2,3)
if you trust the source, use
eval(a)
if you don't trust it, you can use, say
tuple(int(x) for x in re.findall("\d+", a))
or, perhaps
tuple(int(x) for x in a[1:-1].split(","))
or some variation thereof.
(if you're using a version older than 2.4, add brackets inside
the tuple() call:
tuple([int(x) for x in a[1:-1].split(",")])
etc.
</F>
More information about the Python-list
mailing list