I have a string:
str = '[\'RED\', \'GREEN\', \'BLUE\']'
I want to parse it to
list = ['RED','GREEN','BLUE']
But, I am unable to do so.
I tried to parse using json.loads:
json.loads(str)
It gave me:
{JSONDecodeError}Expecting value: line 1 column 2 (char 1)
You can use ast.literal_eval
. eval
can be dangerous on untrusted strings. You ast.literal_eval
which evaluates only valid python structures.
import ast
s = '[\'RED\', \'GREEN\', \'BLUE\']'
ast.literal_eval(s)
# ['RED', 'GREEN', 'BLUE']
You can use python's in-built function eval() . This works for conversion to python's other default data structures(dict, tuples, etc) as well. Something like:
str = '[\'RED\', \'GREEN\', \'BLUE\']'
l = eval(str)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.