Linus Svendsson
Linus Svendsson

Reputation: 1477

converting a string to a list of tuples

I need to convert a string, '(2,3,4),(1,6,7)' into a list of tuples [(2,3,4),(1,6,7)] in Python. I was thinking to split up at every ',' and then use a for loop and append each tuple to an empty list. But I am not quite sure how to do it. A hint, anyone?

Upvotes: 9

Views: 14214

Answers (4)

jsbueno
jsbueno

Reputation: 110301

Without ast or eval:

def convert(in_str):
    result = []
    current_tuple = []
    for token in in_str.split(","):
        number = int(token.replace("(","").replace(")", ""))
        current_tuple.append(number)
        if ")" in token:
           result.append(tuple(current_tuple))
           current_tuple = []
    return result

Upvotes: 5

Gonzalo
Gonzalo

Reputation: 882

Without ast:

>>> list(eval('(2,3,4),(1,6,7)'))
    [(2, 3, 4), (1, 6, 7)]

Upvotes: 3

Scott Hunter
Scott Hunter

Reputation: 49803

Just for completeness: soulcheck's solution, which meets the original poster's requirement to avoid ast.literal_eval:

def str2tupleList(s):
    return eval( "[%s]" % s )

Upvotes: 1

Sven Marnach
Sven Marnach

Reputation: 601679

>>> list(ast.literal_eval('(2,3,4),(1,6,7)'))
[(2, 3, 4), (1, 6, 7)]

Upvotes: 20

Related Questions