I am trying to convert a list enclosed in a quotes to a list. Is their any optimal way to do this.
Ex: list = "[1,2,3,4,5]"
Operation : Convert list which is string to a list
o/p: list = [1,2,3,4,5]
I am trying to convert a list enclosed in a quotes to a list. Is their any optimal way to do this.
Ex: list = "[1,2,3,4,5]"
Operation : Convert list which is string to a list
o/p: list = [1,2,3,4,5]
You can use ast.literal_eval()
to safely evaluate the string:
Safely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None.
In [1]: from ast import literal_eval
In [2]: literal_eval("[1,2,3,4,5]")
Out[2]: [1, 2, 3, 4, 5]
I'd, personally, use JSON for this as it would be the appropriate library for storing and retrieving lists and dictionaries:
import json
li = "[1,2,3,4,5]"
li = json.loads(li)
print(li)
Alternatively, you could use eval
, but it's not recommended:
li = "[1,2,3,4,5]"
li = eval(li)
print(li)
eval is evil use ast.literal_eval
:
>>> import ast
>>> ast.literal_eval("[1,2,3,4,5]")
[1, 2, 3, 4, 5]
Most direct:
li = eval("[1,2,3,4,5]")
list
is a reserved keyword, don't use it as a variable name.
Only use eval
if your string comes from a trusted source; if you call eval
on a string like "import subprocess;subprocess.run('rm -rf /')"
, you're going to have problems.