Convert string to tuple list

I need to convert the string, '(2,3,4),(1,6,7)' to a list of tuples [(2,3,4),(1,6,7)] in Python. I thought to separate everything ',' and then use a for loop and add each tuple to an empty list. But I'm not quite sure how to do this. Hint, anyone?

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

For completeness only: soulcheck solution that meets the original requirements for posters to avoid ast.literal_eval:

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

Without aster or eval:

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

Source: https://habr.com/ru/post/1386124/


All Articles