3

Possible Duplicate:
Converting a string that represents a list, into an actual list object

Having a string like this:

"[81, 102, 114, 132, 194, 210, 228, 317, 357, 358, 379, 396, 407, 417, 418, 420, 470, 471, 506, 526, 533, 538]"

How can I parse it easily into the corresponding list?

I know I could use the re module or splitting by ", ", etc.

Is there any already existing function to do it?

Community
  • 1
  • 1
Flavius
  • 13,566
  • 13
  • 80
  • 126

3 Answers3

5

Use ast.literal_eval():

>>> import ast
>>> s = "[81, 102, 114, 132, 194, 210, 228, 317, 357, 358, 379, 396, 407, 417, 418, 420, 470, 471, 506, 526, 533, 538]"
>>> ast.literal_eval(s)
[81, 102, 114, 132, 194, 210, 228, 317, 357, 358, 379, 396, 407, 417, 418, 420, 470, 471, 506, 526, 533, 538]
NPE
  • 486,780
  • 108
  • 951
  • 1,012
1
>>> l = "[81, 102, 114, 132]"
>>> map(int, l.strip("[]").split(", "))
[81, 102, 114, 132]

For Python 3+ you need to make list from map iterator:

>>> l = "[81, 102, 114, 132]"
>>> list(map(int, l.strip("[]").split(", ")))
[81, 102, 114, 132]
Alexey Kachayev
  • 6,106
  • 27
  • 24
0

The most direct way is to use eval(). That's often considered bad practice, though, because it can lead to security problems.

PeterBB
  • 343
  • 2
  • 9