1

e.g.:

from : "[1,2,3]"to [1,2,3]

as the function int() makes a "5" a 5

Jsphlfvr
  • 13
  • 2

2 Answers2

5

The json and ast packages can help with parsing like this. In this case try:

import json
foo = json.loads("[1,2,3]")

or

import ast
foo = ast.literal_eval("[1,2,3]")

@Sid asks an important question in the comments:

Why not use eval() as it is baked in and would not require the import?

While it is technically true that:

foo = eval("[1,2,3]")

also produces the desired result in this case, @AndyLester importantly reminds us that eval() can be dangerous. Specifically eval() allows for execution of code not just parsing of literals. If we imagine that the following could be any arbitrary block of python and someone could pollute our input with it:

"print('Here be Dragons')"

Then the first two methods will throw exceptions:

foo = json.loads("print('Here be Dragons')")
>>>json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

and

foo = ast.literal_eval("print('Here be Dragons')")
>>>ValueError: malformed node or string:

While the third does

foo = eval("print('Here be Dragons')")
>>>Here be Dragons

our input was executed (dangerous) rather than simply parsed and worse, foo also is still None as print() has no return value.

JonSG
  • 10,542
  • 2
  • 25
  • 36
1

This will correctly parse your list

k = '[1,2,3]'
list(map(lambda x: int(x), k[1:-1].split(',')))

Yields:

[1, 2, 3]
itprorh66
  • 3,110
  • 4
  • 9
  • 21
  • Great answer for "strings"! I *think* the request was for an array of int though. Easy enough to fix with a comprehension :-) – JonSG Apr 16 '21 at 17:00
  • The question was how to make a string which contains a list into a list array. This solution does exactly that. – itprorh66 Apr 16 '21 at 19:05
  • The question specifies `"[1,2,3]"` to `[1,2,3]`. This answer does not do that. This slight modification would allow the expected result `[int(i) for i in k[1:-1].split(',')]` – JonSG Apr 16 '21 at 19:07