Parsing tuple from string?

George Sakkis george.sakkis at gmail.com
Thu Apr 24 01:15:42 EDT 2008


On Apr 24, 12:21 am, Daniel <the.d... at gmail.com> wrote:

> On Apr 23, 4:22 pm, George Sakkis <george.sak... at gmail.com> wrote:> On Apr 23, 6:24 pm, Daniel <the.d... at gmail.com> wrote:
>
> > > I have a list of strings, which I need to convert into tuples.  If the
> > > string is not in python tuple format (i.e. "('one', 'two')", "("one",
> > > 'two')", etc.), then I can just make it a 1-tuple (i.e. return
> > > (string,) ).  If it is in python tuple format, I need to parse it and
> > > return the appropriate tuple (it's ok to keep all tuple elements as
> > > strings).
>
> > > I think eval() will work for this, but I don't know what will be in
> > > the string, so I don't feel comfortable using that.
>
> > Check out one of the safe restricted eval recipes, e.g.http://preview.tinyurl.com/6h7ous.
>
> Thank you very much!

You're welcome. By the way, there's a caveat: simple_eval() doesn't
require a comma between tuple/list elements or dict pairs:

>>> simple_eval('(2 3)')
(2, 3)
>>> simple_eval('[1 2 ,3]')
[1, 2, 3]
>>> simple_eval('{ 1:"a" 2:"b"}')
{1: 'a', 2: 'b'}

Also parenthesized values are evaluated as 1-tuples
>>> simple_eval('(2)')
(2,)

Since it doesn't evaluate general expressions anyway, that's not
necessarily a problem. In any case, making it strict is left as an
exercise to the reader :)

George



More information about the Python-list mailing list