NightmaresCoding
NightmaresCoding

Reputation: 131

Converting String of a tuple to a Tuple

If I have a string that looks like a tuple how can I make it into a tuple?

s = '(((3,),(4,2),(2,)),((1,),(2,4),(2,)))'

and I want to make it into a tuple that contains other tuples.

t = tuple((((3,),(4,2),(2,)),((1,),(2,4),(2,))))

Doesn't work because it makes even the ( as a item in the tuple.

Upvotes: 3

Views: 92

Answers (1)

Padraic Cunningham
Padraic Cunningham

Reputation: 180411

You need to use ast.literal_eval:

from ast import literal_eval
s = '(((3,),(4,2),(2,)),((1,),(2,4),(2,)))'

t = literal_eval(s)
print(t)
print(type(t))
(((3,), (4, 2), (2,)), ((1,), (2, 4), (2,)))
<class 'tuple'>

Upvotes: 10

Related Questions