【问题标题】:How to get the content inside string in python [duplicate]如何在python中获取字符串中的内容[重复]
【发布时间】:2019-06-08 04:19:09
【问题描述】:

我在python中有字符串变量

variable = "[['Acc',{'b':1,'s':1}],['ABC',{'c':1,'d':1}]]"

这个变量的类型是<class 'str'>

我想输出为 result = [['Acc',{'b':1,'s':1}],['ABC'],{'c':1,'d':1}] 应该是<class 'list'>

我不知道如何得到这个。请帮帮我。

【问题讨论】:

    标签: python string list type-conversion


    【解决方案1】:

    ast.literal_eval - 安全地计算表达式节点或包含 Python 文字或容器显示的字符串。提供的字符串或节点只能由以下 Python 文字结构组成:字符串、字节、数字、元组、列表、字典、集合、布尔值、无、字节和集合。

    import ast
    
    variable = "[['Acc',{'b':1,'s':1}],['ABC'],{'c':1,'d':1}]"
    list1 = ast.literal_eval(variable)
    
    print(list1)
    print(type(list1))
    

    O/P:

    [['Acc', {'b': 1, 's': 1}], ['ABC'], {'c': 1, 'd': 1}]
    <class 'list'>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-12
      • 2016-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-03
      • 2011-12-23
      • 2015-11-04
      相关资源
      最近更新 更多