0

I retrieved the sting below form mysql table using python and I am having difficulty converting it into a list.

_string='[1,2,3,4]'

My attempt

>>> _string='[1,2,3,4]'
>>> sum(list(_string),[])
>>> list(_string)
['[', '1', ',', '2', ',', '3', ',', '4', ']']

>>> _string.strip('\n')
'[1,2,3,4]'

Desired output:

[1,2,3,4]

Is there and efficient way to get the desired output? as I will be doing a millions.

user2274879
  • 349
  • 1
  • 5
  • 16

4 Answers4

3

Its what that ast.literal_eval is for,you can simply use it to safely evaluating strings containing Python values :

>>> _string='[1,2,3,4]'
>>> 
>>> import ast
>>> ast.literal_eval(_string)
[1, 2, 3, 4]
Mazdak
  • 105,000
  • 18
  • 159
  • 188
1

Generalizing a bit - if your string is always a JSON formatted list, you could go with:

data = json.loads('[1, 2, 3, 4]')
OrenD
  • 1,751
  • 13
  • 12
0

Try this:

your_list = _string.strip("[]").split(",")
shaktimaan
  • 1,769
  • 13
  • 14
0

Using List comprehension and split

In [14]: [int(i) for i in _string[1:-1].split(',')]
Out[14]: [1, 2, 3, 4]
Ajay
  • 5,267
  • 2
  • 23
  • 30