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
Without ast:
>>> list(eval('(2,3,4),(1,6,7)'))
[(2, 3, 4), (1, 6, 7)]
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 )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.