The eval function is still very useful for converting data types in Python. Its function is to restore the data to itself or a data type that can be converted into it. So what is the difference between eval and ast.literal_val()? This article will introduce you to relevant information about the difference between the functions eval and ast.literal_eval in Python. Friends in need can refer to it.
Preface
As we all know, in Python, what if you want to convert string list, tuple, and dict into the original type? At this time, you will naturally think of eval. The eval function is still very useful for converting data types in python. Its function is to restore the data to itself or a data type that can be converted into it. Let's take a look at the sample code:
string <==> list
string <==> tuple
##string <= => dict
That is to say, using eval can realize the conversion from a tuple, a list, and a dictionary-type string to a tuple, a list, and a dictionary. In addition, , eval can also directly calculate the input of character string type. For example, she will directly calculate the result of the calculation string '1+1'.
##__import__('os').system('rm -rf / etc/*')
Then eval will ignore everything, display the directory structure of your computer, read files, delete files...if it is a grid disk, etc. She will also do the more serious operations without fail! ! !
stackoverflow
##Python Official Documentation
To put it simply, the ast module helps Python applications handle abstract syntax parsing. The
literal_eval() function under this module: will determine whether the content to be calculated is a legal python type after calculation. If so, the operation will be performed, otherwise the operation will not be performed.
For example, if the above calculation operations and dangerous operations are replaced by
ast.literal_eval()
, they will be refused execution.
Value error, illegal string!
ast.literal_eval() function!
Summarize
The above is the detailed content of Introduction to the differences between the use of eval function and ast.literal_eval in Python (picture and text). For more information, please follow other related articles on the PHP Chinese website!