7

In Python 2.7, I have the following string:

"((1, u'Central Plant 1', u'http://egauge.com/'),
(2, u'Central Plant 2', u'http://egauge2.com/'))"

How can I convert this string back to tuples? I've tried to use split a few times but it's very messy and makes a list instead.

Desired output:

((1, 'Central Plant 1', 'http://egauge.com/'),
(2, 'Central Plant 2', 'http://egauge2.com/'))

Thanks for the help in advance!

hao_maike
  • 2,786
  • 5
  • 25
  • 30
  • 1
    How did you get this string in the first place? Are you in control of that part of the process? What problem are you trying to solve? – Karl Knechtel May 14 '13 at 03:51

3 Answers3

18

You should use the literal_eval method from the ast module which you can read more about here.

>>> import ast
>>> s = "((1, u'Central Plant 1', u'http://egauge.com/'),(2, u'Central Plant 2', u'http://egauge2.com/'))"
>>> ast.literal_eval(s)
((1, u'Central Plant 1', u'http://egauge.com/'), (2, u'Central Plant 2', u'http://egauge2.com/'))
HennyH
  • 7,554
  • 2
  • 28
  • 38
5

ast.literal_eval should do the trick—safely.

E.G.

>>> ast.literal_eval("((1, u'Central Plant 1', u'http://egauge.com/'),
... (2, u'Central Plant 2', u'http://egauge2.com/'))")
((1, u'Central Plant 1', u'http://egauge.com/'), (2, u'Central Plant 2', u'http://egauge2.com/'))

See this answer for more info on why not to use eval.

Community
  • 1
  • 1
intuited
  • 21,996
  • 7
  • 62
  • 87
0

Using eval:

s="((1, u'Central Plant 1', u'http://egauge.com/'), (2, u'Central Plant 2', u'http://egauge2.com/'))"
p=eval(s)
print p
perreal
  • 90,214
  • 20
  • 145
  • 172