Convert String to List in Python Without Using Eval?

前端 未结 4 1241
粉色の甜心
粉色の甜心 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 06:12

    Try to use the json module:

    import json
    s = "[['Cheese', 72], ['Milk', 45], ['Bread', 22]]"
    s = s.replace("'", '"')
    print json.loads(s)
    

提交回复
热议问题