Home  >  Article  >  Backend Development  >  The role of eval function in python

The role of eval function in python

尚
Original
2019-10-21 17:31:3431734browse

The role of eval function in python

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

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

eval() method 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.

Usage examples:

1. Convert string to list

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

2. Convert string to dictionary

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

3. Convert string to tuple

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 role of 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