Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python string to list best practice

I have a string like this "['first', 'sec', 'third']"

What would be the best way to convert this to a list of strings ie. ['first', 'sec', 'third']

like image 478
Ruth Avatar asked Aug 06 '13 10:08

Ruth


1 Answers

I'd use literal_eval(), it's safe:

Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.

This can be used for safely evaluating strings containing Python expressions from untrusted sources without the need to parse the values oneself.

>>> import ast
>>> ast.literal_eval("['first', 'sec', 'third']")
['first', 'sec', 'third']

It doesn't eval anything except literal expressions:

>>> ast.literal_eval('"hello".upper()')
...
ValueError: malformed string

>>> ast.literal_eval('"hello"+" world"')
...
ValueError: malformed string
like image 124
alecxe Avatar answered Sep 30 '22 13:09

alecxe