Dendory
Dendory

Reputation: 630

Python: String to list (without split)

I have Python lists saved as string representations like this:

a = "['item 1', 'item 2', 'item 3']"

and I'd like to convert that string to a list object. I tried to just load it directly, or use list(a) but it just splits every character of the string. I suppose I could manually parse it by removing the first character, removing the last one, splitting based on , and then remove the single quotes.. but isn't there a better way to convert it directly since that string is an exact representation of what a list looks like?

Upvotes: 2

Views: 25890

Answers (1)

C.B.
C.B.

Reputation: 8346

Use the ast module

>>> import ast
>>> list_as_string = "['item 1', 'item 2', 'item 3']"
>>> _list = ast.literal_eval(list_as_string)
>>> _list
['item 1', 'item 2', 'item 3']
>>>

Upvotes: 13

Related Questions