Python Forum

Full Version: String to list
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Consider this string
'[1,2]'
I am trying to convert it to
[1,2]

I tried some string and list functions, but nothing worked.

Looking for a simple way to perform the conversion. Any suggestions welcome.
You could use eval('[1, 2]'). In some applications that can lead to security flaws, so it gets frowned upon.

Another options is to strip the brackets with slicing and then split on the comma. text[1:-1].split(','). That will give you a list of strings, not a list of ints, but you can convert them to ints with a loop of list comprehension.
A bit different way:
>>> '[1, 2]'.strip('[]').split(',')
['1', ' 2']
>>> 
An obvious answer, create it as a list, [1,2], in the first place.
There is also a safe eval:
import ast
ast.literal_eval('[1,2]')
or assuming the initial list is json data
import json
json.loads('[1,2]')