Eli Eli - 5 months ago 8
Python Question

Parse a tuple from a string?

Say I have a string that's of the same form a tuple should be, for example,

. What's the easiest way to convert that into an actual tuple? An example of what I want to do is:

tup_string = "(1,2,3,4,5)"
tup = make_tuple(tup_string)

Just running
on the string make the whole thing one big tuple, whereas what I'd like to do is comprehend the string as a tuple. I know I can use a regex for this, but I was hoping there's a less costly way. Ideas?


It already exists!

>>> from ast import literal_eval as make_tuple
>>> make_tuple("(1,2,3,4,5)")
(1, 2, 3, 4, 5)

Be aware of the corner-case, though:

>>> make_tuple("(1)")
>>> make_tuple("(1,)")

If your input format works different than Python here, you need to handle that case separately or use another method like tuple(int(x) for x in tup_string[1:-1].split(',')).