Parse a tuple from a string?

Solution 1:

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)")
1
>>> make_tuple("(1,)")
(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(',')).

Solution 2:

I would recommend using literal_eval.

If you are not comfortable with literal_eval or want to have more control on what gets converted you can also disassemble the string, convert the values and recreate the tuple.

Sounds more complicated than it is, really, it's a one-liner:

eg = '(102,117,108)'
eg_tuple = map(int, eg.replace('(','').replace(')','').split(',')))

This would throw a ValueError if any element (string) in the tuple is not convertible to int, like, for example the '1.2' in the string: '(1.2, 3, 4)'.


The same can be achieved with regex:

import re
eg = '(102,117,108)'
et_tuple = tuple(map(int, re.findall(r'[0-9]+', eg)))

Solution 3:

You can parse your string without SyntaxError

def parse_tuple(string):
    try:
        s = eval(string)
        if type(s) == tuple:
            return s
        return
    except:
        return

This function return the Tuple if parse is success. Otherwise return None.

print parse_tuple("('A', 'B', 'C')")