【问题标题】:How to convert tuple in string to tuple object?如何将字符串中的元组转换为元组对象?
【发布时间】:2013-05-14 00:29:27
【问题描述】:

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

提前感谢您的帮助!

【问题讨论】:

  • 你是怎么得到这个字符串的?你能控制这部分过程吗?你想解决什么问题?

标签: python tuples


【解决方案1】:

您应该使用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/'))

【讨论】:

    【解决方案2】:

    ast.literal_eval 应该可以解决问题——安全地

    例如

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

    请参阅this answer,了解有关为什么使用eval的更多信息。

    【讨论】:

      【解决方案3】:

      使用评估:

      s="((1, u'Central Plant 1', u'http://egauge.com/'), (2, u'Central Plant 2', u'http://egauge2.com/'))"
      p=eval(s)
      print p
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-04-30
        • 2016-03-14
        • 2022-11-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多