-2

Now I have a string like this:

data = "[[1,'00007',0.19],[2,'00008',0.29],[3,'00009',0.49],[4,'00010',0.59]]"

print(type(data))

<class 'str'>

in python this is like data array out,but it is a string, now I want convert this string to the real data array <class 'list'> , How should I do this

styvane
  • 59,869
  • 19
  • 150
  • 156
Meng Qian
  • 97
  • 1
  • 1
  • 9

3 Answers3

2

You could do

eval(data)

to parse its content.

elzell
  • 2,228
  • 1
  • 16
  • 26
2

Use ast.literal_eval: as the documentation says-

Safely evaluate an expression node or a Unicode or Latin-1 encoded string containing a Python literal or container display.

The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.

>>> import ast

>>> data = "[[1,'00007',0.19],[2,'00008',0.29],[3,'00009',0.49],[4,'00010',0.59]]"
>>> ast.literal_eval(data)
[[1, '00007', 0.19], [2, '00008', 0.29], [3, '00009', 0.49], [4, '00010', 0.59]]

>>> print(type(ast.literal_eval(data)))
>>> <type 'list'>

Avoid using eval unless truly needed. Details at.

Community
  • 1
  • 1
Learner
  • 5,192
  • 1
  • 24
  • 36
0

Following on from your definition of data:

data_list = data.replace("[","").replace("]","").replace("'","").split(",")
new_list = [data_list[x:x+3] for x in range(0, len(data_list), 3)]

Though everything in the result is now a string.

Chris Geatch
  • 113
  • 6