0

I have a string like: string = "[1, 2, 3]"

I need to convert it to a list like: [1, 2, 3]

I've tried using regular expression for this purpose, but to no avail

3 Answers3

4
string = "[1, 2, 3]"

import ast
ast.literal_eval(string)

would evaluate to [1, 2, 3].

etnguyen03
  • 580
  • 4
  • 19
2

Try [int(x) for x in arr.strip("[]").split(", ")], or if your numbers are floats you can do [float(x) for x in arr.strip("[]").split(", ")]

duncster94
  • 570
  • 6
  • 23
1

If you can guarantee that your string value comes from a safe source or if it is just an academic thing, you can make use of eval (as pointed out in the comments for this answer).

>>> str_value = "[1, 2, 3]"
>>> list_value = eval(str_value)
>>> type(list_value)
<class 'list'>
>>> list_value[0]
1

As per the documentation, when using eval, the expression argument is parsed and evaluated as a python expression, so this can lead to malicious code execution, depending on the context you are planning to use such evaluation.

>>> str_value = "print('hello')"
>>> eval(str_value)
hello

If you cannot guarantee such source or if your actual intent is evaluating python literal expressions, you can make use of ast.literal_eval (as pointed out in the comments for this answer).

>>> import ast
>>> str_value = "[1, 2, 3]"
>>> list_value = ast.literal_eval(str_value)
>>> type(list_value)
<class 'list'>
>>> list_value[0]
1

As per the documentation, when using ast.literal_eval, the string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None., so it can be evaluated without leading to malicious code execution.

>>> str_value = "print('hello')"
>>> ast.literal_eval(str_value)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  [...]
  File "/usr/lib/python3.8/ast.py", line 63, in _raise_malformed_node
    raise ValueError(f'malformed node or string: {node!r}')
ValueError: malformed node or string: <_ast.Call object at 0x7f4b0d501a00>

dandev486
  • 4,143
  • 2
  • 14
  • 22
  • 1
    `eval` can be dangerous, because the string _could_ have malicious code in it. Usually, `eval` can be replaced with something else. In this case, using `ast.literal_eval` or string methods would be safer (and better imho). If you edit this answer with some caveats about `eval`, I'll happily remove the downvote. – jkr Dec 07 '20 at 23:29
  • @jakub, thank you very much for the clarification, you are correct! – dandev486 Dec 07 '20 at 23:38