Devin Roberts
Devin Roberts

Reputation: 11

Python - Obtain a list of parenthetical tuples from string

I have a string such as: (1,2,3,'4.1),(4.2)',5,6,7),(8,9,10). The output I need to obtain is the list: [ ((1,2,3,'4.1),(4.2)',5,6,7), (8,9,10) ] I believe I need a regex in order to perform this task. How can I do so?

Thank you.

Upvotes: 1

Views: 129

Answers (1)

Jared Goguen
Jared Goguen

Reputation: 9010

You might be able to evaluate the string directly (after putting it in a list).

from ast import literal_eval

string = "(1,2,3,'4.1),(4.2)',5,6,7),(8,9,10)"

literal_eval('[{}]'.format(string))
# [(1, 2, 3, '4.1),(4.2)', 5, 6, 7), (8, 9, 10)]

Upvotes: 2

Related Questions