In Python 2.7, I have the following string:
在Python 2.7中,我有以下字符串:
"((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!
我在这里先向您的帮助表示感谢!
3 个解决方案
#1
11
You should use the literal_eval
method from the ast
module which you can read more about here.
您应该使用ast模块中的literal_eval方法,您可以在这里阅读更多信息。
>>> 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/'))
#2
3
ast.literal_eval
should do the trick—safely.
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/'))
See this answer for more info on why not to use eval
.
有关为何不使用eval的详细信息,请参阅此答案。
#3
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
#1
11
You should use the literal_eval
method from the ast
module which you can read more about here.
您应该使用ast模块中的literal_eval方法,您可以在这里阅读更多信息。
>>> 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/'))
#2
3
ast.literal_eval
should do the trick—safely.
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/'))
See this answer for more info on why not to use eval
.
有关为何不使用eval的详细信息,请参阅此答案。
#3
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