How to cast string back into a list

casting, list, python, string

Solution

The easiest and safest way would be to use `ast.literal_eval()`:

import ast

ab = [1, 2, 'a', 'b', 'c']    # a list
strab = str(ab)               # the string representation of a list
strab
=> "[1, 2, 'a', 'b', 'c']"

lst = ast.literal_eval(strab) # convert string representation back to list
lst
=> [1, 2, 'a', 'b', 'c']

ab == lst                     # sanity check: are they equal?
=> True                       # of course they are!

Notice that calling `eval()` also works, but it's not safe and you should not use it:

eval(strab)
=> [1, 2, 'a', 'b', 'c']

Problem

I have a list: ``` ab = [1, 2, a, b, c] ``` I did: ``` strab = str(ab). ``` So `strab` is now a string. I want to cast that string back into a list. How can I do that?

Original source

Related problems