在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)
ast.literal_eval应该安全地完成这个技巧\xe2\x80\x94 。
例如
\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/\'))\nRun Code Online (Sandbox Code Playgroud)\n\n有关为什么不使用 的更多信息,请参阅此答案。eval
| 归档时间: |
|
| 查看次数: |
2786 次 |
| 最近记录: |