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
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
string = "[1, 2, 3]"
import ast
ast.literal_eval(string)
would evaluate to [1, 2, 3]
.
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(", ")]
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>