Parsing tuple from string?

Daniel the.doag at gmail.com
Wed Apr 23 18:24:02 EDT 2008


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




More information about the Python-list mailing list