Parsing tuple from string?

D

Daniel

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.

I tried coming up with a regex, but the best I can get with my limit
knowledge right now is:
matches = re.match("\(['\"](.*)['\"], ['\"](.*)['\"]\)", string)

which works well enough for my purposes (even though I know it's far
from proper), except that it only captures as 2-tuples, and I need to
be able to capture n-tuples. Can someone help point me to the correct
re or a better way to solve this?

Thanks in advance,
Daniel
 
G

George Sakkis

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.

HTH,
George
 
G

George Sakkis

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(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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top