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?
>>> list(ast.literal_eval('(2,3,4),(1,6,7)'))
[(2, 3, 4), (1, 6, 7)]
Without ast 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
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 )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With