Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list string to list

Tags:

python

I have a string:

s= "[7, 9, 41, [32, 67]]"

and I need to convert that string into a list:

l= [7, 9, 41, [32, 67]]

the problem is, when I use list(s) I get this:

['[', '7', ',', ' ', '9', ',', ' ', '4', '1', ',', ' ', '[', '3', '2', ',', ' ', '6', '7', ']', ']']

I am using python 3.2

like image 861
Parker Hoyes Avatar asked Jun 27 '26 23:06

Parker Hoyes


1 Answers

You can do exactly what you asked for by using ast.literal_eval():

>>> ast.literal_eval("[7, 9, 41, [32, 67]]")
[7, 9, 41, [32, 67]]

However, you probably want to use a sane serialisation format like JSON in the first place, instead of relying on the string representation of Python objects. (As a side note, the string you have might even be JSON, since the JSON representation of this particular object would look identical to the Python string representation. Since you did not mention JSON, I'm assuming this is not what you used to get this string.)

like image 152
Sven Marnach Avatar answered Jun 30 '26 13:06

Sven Marnach



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!