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']
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']
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
ast.literal_eval() is safe, as opposed to eval(). That said, the best option is probably to store your data in a more standardised format, if possible.If they're always formatted as you say all the strings are quoted in the same fashion, a simple split should do it, too:
"['first', 'sec', 'third']".split("'")[1::2]
This solution is much more fragile, as it will support only a single quoting style.
It is considerably faster, though.
%timeit "['first', 'sec', 'third']".split("'")[1::2]
1000000 loops, best of 3: 726 ns per loop
%timeit ast.literal_eval("['first', 'sec', 'third']")
10000 loops, best of 3: 21.8 us per loop