6

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

事前に助けてくれてありがとう!

4

3 に答える 3

16

ここで詳細を読むことができるモジュールの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/'))
于 2013-05-14T00:34:55.623 に答える
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
于 2013-05-14T00:33:05.100 に答える