2

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?

2
  • 1
    a.lstrip('[').rstrip(']').split(',')[0]. Maybe also look at regex, it;ll be useful in the future ;) Commented May 28, 2015 at 15:01
  • a[1:-1].split(",") simple slicing also woks fine Commented Nov 30, 2021 at 11:06

1 Answer 1

13

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']
>>>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.