如何将字符串中的元组转换为元组对象?

hao*_*ike 5 python tuples

在Python 2.7中,我有以下字符串:

"((1, u'Central Plant 1', u'http://egauge.com/'),
(2, u'Central Plant 2', u'http://egauge2.com/'))"
Run Code Online (Sandbox Code Playgroud)

如何将此字符串转换回元组?我曾尝试使用split几次,但它非常混乱,而是制作一个列表.

期望的输出:

((1, 'Central Plant 1', 'http://egauge.com/'),
(2, 'Central Plant 2', 'http://egauge2.com/'))
Run Code Online (Sandbox Code Playgroud)

我在这里先向您的帮助表示感谢!

Hen*_*nyH 11

您应该使用模块中的literal_eval方法ast,您可以在这里阅读更多信息.

>>> 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/'))
Run Code Online (Sandbox Code Playgroud)


int*_*ted 5

ast.literal_eval应该安全地完成这个技巧\xe2\x80\x94 。

\n\n

例如

\n\n
>>> ast.literal_eval("((1, u\'Central Plant 1\', u\'http://egauge.com/\'),\n... (2, u\'Central Plant 2\', u\'http://egauge2.com/\'))")\n((1, u\'Central Plant 1\', u\'http://egauge.com/\'), (2, u\'Central Plant 2\', u\'http://egauge2.com/\'))\n
Run Code Online (Sandbox Code Playgroud)\n\n

有关为什么使用 的更多信息,请参阅此答案eval

\n