eval
功能:将字符串str当成有效的表达式来求值并返回计算结果。
语法:?eval(source[,globals[,locals]]) -> value
参数:
source:一个Python表达式或函数compile()返回的代码对象
globals:可选。?变量作用域,全局命名空间,如果被提供,则必须是一个字典对象。
locals:可选。?变量作用域,局部命名空间,如果被提供,可以是任何映射对象。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
可以把
list
,
tuple
,
dict
和string相互转化。
#################################################
字符串转换成列表
a?
= ?
"[[1,2],[3,4],[5,6],[7,8],[9,0]]"
type
(a)
# <type ‘str‘>
b?
= ?
eval
(a)
print
(b)
# [[1,0]]
type
(b)
# <type ‘list‘>
#################################################
字符串转换成字典
a?
= ?
"{1: ‘a‘,2: ‘b‘}"
type
(a)
# <type ‘str‘>
b?
= ?
eval
(a)
print
(b)
#{1: ‘a‘,2: ‘b‘}
type
(b)
# <type ‘dict‘>
#################################################
字符串转换成元组
a?
= ?
"([1,(9,0))"
type
(a)
# <type ‘str‘>
b?
= ?
eval
(a)
print ?
(b)
([
1
,?
2
],[
3
,?
4
],[
5
,?
6
],[
7
,?
8
],(
9
,?
0
))
type
(b)
# <type ‘tuple‘># 计算公式值x = 7 eval( ‘3 * x‘ ) # 21 eval(‘pow(2,2)‘) # 4eval(‘2 + 2‘) # 4
|