eval()函数就是实现list、dict、tuple、与str之间的转化:
示例:
>>>x = 7
>>> eval( '3 * x' )
21
>>> eval('pow(2,2)')
4
>>> eval('2 + 2')
4
>>> n=81
>>> eval("n + 4")
85
eval()函数在Python中的作用:
1、字符转换为列表:
a = “[[1,2], [3,4], [5,6], [7,8], [9,0]]”
print(type(a))
b = eval(a)print(type(b))
print(b)
2、字符串转换为字典
a = "{1: 'a', 2: 'b'}"
print(type(a))b = eval(a)
print(type(b))
print(b)
3、字符转换为元组
a = "([1,2], [3,4], [5,6], [7,8], (9,0))"
print(type(a))b=eval(a)
print(type(b))
print(b)
语法:
eval(expression[, globals[, locals]])
参数:
expression – 表达式。
globals – 变量作用域,全局命名空间,如果被提供,则必须是一个字典对象。
locals – 变量作用域,局部命名空间,如果被提供,可以是任何映射对象。
遇到的问题
line.strip().decode(encoding_type)
Out[14]: '"2'
eval(line.strip().decode(encoding_type))
Traceback (most recent call last):
File "D:\python3.8.5\lib\site-packages\IPython\core\interactiveshell.py", line 3418, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-15-ed3cf673db78>", line 1, in <module>
eval(line.strip().decode(encoding_type))
File "<string>", line 1
"2
^
SyntaxError: EOL while scanning string literal