9

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
1

4 Answers 4

20
>>> list(ast.literal_eval('(2,3,4),(1,6,7)'))
[(2, 3, 4), (1, 6, 7)]
answered Dec 13, 2011 at 14:37
Sign up to request clarification or add additional context in comments.

8 Comments

+1 was about to post similar solution, but wrapping the string in [] and using eval. This looks much nicer.
I would like to do it without the ast.literal_eval.
because i haven't learnt about many of the built-in functions.. can you help?
@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?
@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.
|
5

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
Kevin M
1983 silver badges13 bronze badges
answered Dec 13, 2011 at 16:02

Comments

3

Without ast:

>>> list(eval('(2,3,4),(1,6,7)'))
 [(2, 3, 4), (1, 6, 7)]
answered Oct 16, 2020 at 0:11

Comments

1

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

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.