Skip to content

Latest commit

 

History

History
16 lines (11 loc) · 501 Bytes

20221214133347.md

File metadata and controls

16 lines (11 loc) · 501 Bytes

From string to object in Python

Here we get a nested list from a string:

>>> s = "[1, 2, [3, 4], [5]]"
>>> import ast
>>> ast.literal_eval(s)
[1, 2, [3, 4], [5]]

The ast.literal_eval() function is a safe way to evaluate a string containing a Python literal or container display. It parses the string to a Python literal (like lists, dicts, tuples, etc.). 🎉

This function is much safer than eval(), which can execute arbitrary code and lead to security vulnerabilities. 💡

#ast