I regret not knowing the role of the eval function in python

In this article, the editor compiled for everyone about the function of eval in python and the example code, friends who need it, please refer to it.

The eval() function is used to execute a string expression and return the value of the expression.

Eval function function: evaluate the string str as a valid expression and return the calculation result. The eval function can realize the conversion between list, dict, tuple and str

The syntax of the eval() method:

1
 
eval(expression[, globals[, locals
 

parameter:

expression - expression.

globals-variable scope, global namespace, if provided, it must be a dictionary object.

locals-variable scope, local namespace, if provided, can be any mapping object.

Example of use:

1. Convert a string to a list

4
5
6
7
8
9
 
a = "[[1,2], [3,4], [5,6], [7,8], [9,0]]"
 
print(type(a))
 
b = eval(a)
 
print(type(b))
 
print(b)
 

2. Convert a string to a dictionary

a = "{1: 'a', 2: 'b'}"
 
print(type(a))
 
b = eval(a)
 
print(type(b))
 
print(b)

3. Convert strings into tuples

a = "([1,2], [3,4], [5,6], [7,8], (9,0))"
 
print(type(a))
 
b=eval(a)
 
print(type(b))
 
print(b)

The above is the detailed content of the eval function in python, thank you for your study.

I am a python development engineer, and I have compiled a set of the latest python system learning tutorials, including basic python scripts to web development, crawlers, data analysis, data visualization, machine learning, and interview books. Those who want these materials can pay attention to the editor, add Q skirt 851211580 to pick up Python learning materials and learning videos, and online guidance from the Great God!

Guess you like

Origin blog.csdn.net/pyjishu/article/details/105417753