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?
Tamás
48.2k12 gold badges107 silver badges125 bronze badges
asked Dec 13, 2011 at 14:35
Linus Svendsson
1,4776 gold badges18 silver badges21 bronze badges
-
possible duplicate of Python convert formatted string to listeumiro– eumiro2011年12月13日 14:42:25 +00:00Commented Dec 13, 2011 at 14:42
4 Answers 4
>>> list(ast.literal_eval('(2,3,4),(1,6,7)'))
[(2, 3, 4), (1, 6, 7)]
answered Dec 13, 2011 at 14:37
Sven Marnach
608k123 gold badges969 silver badges866 bronze badges
Sign up to request clarification or add additional context in comments.
8 Comments
soulcheck
+1 was about to post similar solution, but wrapping the string in [] and using eval. This looks much nicer.
Linus Svendsson
I would like to do it without the ast.literal_eval.
Linus Svendsson
because i haven't learnt about many of the built-in functions.. can you help?
Sven Marnach
@LinusSvendsson: Then you have just learned about a new one. :) Well, anyway, when trying to provide a different solution, how would I know which function I am allowed to use, and which ones you would also reject?
Sven Marnach
@LinusSvendsson: Sorry, I can't read your code. And the alleged result isn't correct Python syntax. Consider to edit your original question or ask a new one.
|
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
answered Dec 13, 2011 at 16:02
jsbueno
114k11 gold badges159 silver badges239 bronze badges
Comments
Without ast:
>>> list(eval('(2,3,4),(1,6,7)'))
[(2, 3, 4), (1, 6, 7)]
Comments
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 )
answered Dec 13, 2011 at 16:00
Scott Hunter
50k12 gold badges65 silver badges107 bronze badges
Comments
lang-py