I have a Python string (str
), which is "['Fish & Chips', 'Fast Food', 'Restaurants']"
.
How can I convert this string to a list?
I have a Python string (str
), which is "['Fish & Chips', 'Fast Food', 'Restaurants']"
.
How can I convert this string to a list?
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
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']