Search code examples
pythonstringlistserialization

Python - String to list


I need cast a list to a string and get back the string to a list. There's a python way to make this behavior?

l1 = ['aa','bb','cc']
s = str(l1)
l2 = cast_string_to_list(s)
print l2
"['aa','bb','cc']"

Solution

  • Use a serialization library like json:

    import json
    
    l1 = ['aa','bb','cc']
    s = json.dumps(l1)
    l2 = json.loads(s)
    
    print s
    print l1 == l2