2013-05-14 17 views
5

In Python 2.7, ho la seguente stringa:Come convertire la tupla in stringa in un oggetto tupla?

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

Come posso convertire questa stringa di nuovo a tuple? Ho provato a usare split un paio di volte ma è molto caotico e crea una lista.

output desiderato:

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

Grazie per l'aiuto in anticipo!

+1

Come hai ottenuto questa stringa in primo luogo? Hai il controllo di quella parte del processo? Che problema stai cercando di risolvere? –

risposta

11

Si dovrebbe utilizzare il metodo literal_eval dal modulo ast che potete leggere di più su 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/')) 
+0

Fantastico, funziona. Grazie! –

0

Utilizzare 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 
3

ast.literal_eval dovrebbe fare il trick- sicurezza.

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/')) 

Vedi this answer per ulteriori informazioni sul motivo per cui non usare eval.