2
l = "['Hello', 'my', 'name', 'is', 'Apple']"
l1 = ['Hello', 'my', 'name', 'is', 'Apple']

type(l) returns str but I want it to be a list, as l1 is.

How can I transform that string into a common list?

2 Answers 2

15

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

Sign up to request clarification or add additional context in comments.

2 Comments

Nice to see the first answer to this question being literal_eval, not the regular dangerous eval.
@sweeneyrod they should just rename eval to evil
0

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(', ')]

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.