2013-05-14 66 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

相关问题