5

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']

1
  • 1
    Best way would be to use a known serialization format, like json. Commented Aug 6, 2013 at 10:42

2 Answers 2

10

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

2 Comments

Thanks alecxe, I've been using this but I am curious to see what people think, other methods etc.
+1 - This is the best way to do it, as 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.
1

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

2 Comments

Cool, but what if the list was "['first', 'sec', 'third', \"fourth\"]" or even L = """['first', 'sec', 'third', "fourth"]"""
Nice examples. I'll let the answer live, I hope it aids showing why literal_eval is the better practice.

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.