Skip to content Skip to sidebar Skip to footer

Python - Convert String To List With Same Structure

I have a Python string (str), which is '['Fish & Chips', 'Fast Food', 'Restaurants']'. How can I convert this string to a list?

Solution 1:

Edit: See snakecharmerb's for a safer alternative to eval().


It seems like you're looking for eval(), which takes a string and evaluates it as a Python expression:

s = "['Fish & Chips', 'Fast Food', 'Restaurants']"eval(s)
# ['Fish & Chips', 'Fast Food', 'Restaurants']type(eval(s))
# list

Solution 2:

While eval works it's safer to use ast.literal_eval if the input data is not trusted:

>>> import ast
>>> s = "['Fish & Chips', 'Fast Food', 'Restaurants']">>> ast.literal_eval(s)
['Fish & Chips', 'Fast Food', 'Restaurants']

Post a Comment for "Python - Convert String To List With Same Structure"