Home  >  Article  >  Backend Development  >  What is the eval function in python

What is the eval function in python

尚
Original
2019-06-28 11:48:3314772browse

What is the eval function in python

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

Syntax:

eval(expression[, globals[, locals]])

Parameters:

expression -- Expression.

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

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

Example:

>>>x = 7
>>> eval( '3 * x' )
21
>>> eval('pow(2,2)')
4
>>> eval('2 + 2')
4
>>> n=81
>>> eval("n + 4")
85

The role of the eval() function in Python:

1. Convert characters to lists:

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

What is the eval function in python

2. Convert string to dictionary

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

What is the eval function in python

3. Convert character to tuple

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

What is the eval function in python

For more Python related technical articles, please visit the Python Tutorial column to learn!

The above is the detailed content of What is the eval function in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn