How to turn a string into a list in python?

前端 未结 2 1258
太阳男子
太阳男子 2021-01-22 03:16
l = \"[\'Hello\', \'my\', \'name\', \'is\', \'Apple\']\"
l1 = [\'Hello\', \'my\', \'name\', \'is\', \'Apple\']

type(l) returns str

相关标签:
2条回答
  • 2021-01-22 03:50

    ast.literal_eval is a nice approach. For those preferint string manipulation, another option is:

    l1 = [x[1:-1] for x in l[1:-1].split(', ')]
    
    0 讨论(0)
  • 2021-01-22 03:51

    the ast module has a literal_eval that does what you want

    import ast
    l = "['Hello', 'my', 'name', 'is', 'Apple']"
    l1 = ast.literal_eval(l)
    

    Outputs:

    ['Hello', 'my', 'name', 'is', 'Apple']
    

    docs

    0 讨论(0)
提交回复
热议问题