2013-05-14 82 views
5

在Python 2.7,我有以下字符串:如何將字符串中的元組轉換爲元組對象?

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

我如何轉換這個字符串回元組?我嘗試過使用split幾次,但它非常混亂,並改爲列表。

所需的輸出:

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

感謝您的幫助提前!

+1

你是如何得到這個字符串的第一個地方?你是否在控制這部分過程?你想解決什麼問題? – 2013-05-14 03:51:44

回答

11

您應該使用從ast模塊literal_eval方法,你可以閱讀更多關於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

太棒了,可以工作。謝謝! – 2013-05-14 00:53:52

0

使用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應該做的花樣 - 安全

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

對於爲什麼不使用eval更多信息請參見this answer

相關問題