Patternite Logo

Transforming Python expressions in a string literal using `ast.literal_eval`


String literals containing valid Python expressions can be mapped to their expressions by using the built-in `ast.literal_eval` function


Occasionally we may encounter Python expressions inside string literals, such as reading in code from a file or API. In these cases we can transform these strings into the underlying expressions using the ast.literal_eval function. literal_eval is a safer alternative to the eval function, and is preferable if the data source (i.e. string_with_list in our example) is not trusted. You can read more about the differences between literal_eval and eval in this Stack Overflow question.

Profile picture for duncster

Patternite © 2022

Patternite Logo