Convert String to List in Python Without Using Eval?

前端 未结 4 1212
粉色の甜心
粉色の甜心 2020-12-21 05:15

I have a string, something like this: \"[[\'Cheese\', 72], [\'Milk\', 45], [\'Bread\', 22]]\".

I want to convert this to a list. I know I can use eval(s

相关标签:
4条回答
  • 2020-12-21 05:48

    If you insist on doing it this way, you can use the ast.literal_eval function.

    >>> import ast
    >>> foo = "[['Cheese', 72], ['Milk', 45], ['Bread', 22]]"
    >>> ast.literal_eval(foo)
    [['Cheese', 72], ['Milk', 45], ['Bread', 22]]
    

    I'm sure others will tell you that you're likely doing something wrong, or to use a library like JSON to transport arbitrary data structures like this one, and I wouldn't disagree.

    0 讨论(0)
  • 2020-12-21 05:50

    Here's one way: exec("list = "+foo) This should make a variable 'list' with the list in string converted to a real list. This also works for dictionaries, arrays, bools, etc in strings.

    0 讨论(0)
  • 2020-12-21 06:03

    You might consider using the json module to deserialize and making sure your strings are in json format.

    See http://docs.python.org/2/library/json.html for details about using this module.

    0 讨论(0)
  • 2020-12-21 06:12

    Try to use the json module:

    import json
    s = "[['Cheese', 72], ['Milk', 45], ['Bread', 22]]"
    s = s.replace("'", '"')
    print json.loads(s)
    
    0 讨论(0)
提交回复
热议问题