User Tools

Site Tools


convert_a_string_to_a_list

Convert a string to a list

ast.literaltype

You can use ast.literaleval from the ast (Abstract Syntax Trees) module.

$ ipython
Python 3.10.6 | packaged by conda-forge | (main, Oct 24 2022, 16:02:16) [MSC v.1916 64 bit (AMD64)]
Type 'copyright', 'credits' or 'license' for more information
IPython 8.4.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]:
s = "['a', 'b', 'c']"

In [2]:
import ast
ast.literal_eval(s)
Out[2]:
['a', 'b', 'c']

In [3]:
type(ast.literal_eval(s))
Out[3]:
list

This is safer than using eval(). From the documentation https://docs.python.org/3/library/ast.html#ast.literal_eval

This function had been documented as “safe” in the past without defining what that meant. That was misleading. This is specifically designed not to execute Python code, unlike the more general eval(). There is no namespace, no name lookups, or ability to call out. But it is not free from attack: A relatively small input can lead to memory exhaustion or to C stack exhaustion, crashing the process. There is also the possibility for excessive CPU consumption denial of service on some inputs. Calling it on untrusted data is thus not recommended.
convert_a_string_to_a_list.txt · Last modified: 2023/02/26 03:28 by raju