string to list of numbers conversion

Paul McGuire ptmcg at
Mon Nov 6 12:06:35 CET 2006

"jm.suresh at" <jm.suresh at> wrote in message 
news:1162730071.953080.284980 at
> Hi,
>  I have a string '((1,2), (3,4))' and I want to convert this into a
> python tuple of numbers. But I do not want to use eval() because I do
> not want to execute any code in that string and limit it to list of
> numbers.
>  Is there any alternative way?
> Thanks.
> Suresh

Pyparsing comes with an example that parses strings representing lists. 
Here's that example, converted to parsing only tuples of numbers.  Note that 
this does not presume that tuples are only pairs, but can be any number of 
numeric values, nested to any depth, and with arbitrary whitespace, etc. 
This grammar also includes converters by type, so that ints come out as 
ints, and floats as floats.  (This grammar doesn't handle empty tuples, but 
it does handle tuples that include an extra ',' after the last tuple 

-- Paul
Download pyparsing at .

from pyparsing import *

integer = (Word(nums)|Word('-+',nums)).setName("integer")
real = Combine(integer + "." + Optional(Word(nums))).setName("real")
tupleStr = Forward().setName("tuple")
tupleItem = real | integer | tupleStr
tupleStr << ( Suppress("(") + delimitedList(tupleItem) +
                       Optional(Suppress(",")) + Suppress(")") )

# add parse actions to do conversion during parsing
integer.setParseAction( lambda toks: int(toks[0]) )
real.setParseAction( lambda toks: float(toks[0]) )
tupleStr.setParseAction( lambda toks: tuple(toks) )

s = '((1,2), (3,4), (-5,9.2),)'
print tupleStr.parseString(s)[0]

((1, 2), (3, 4), (-5, 9.1999999999999993))

More information about the Python-list mailing list