描述
eval()
函数用来执行一个字符串表达式,并返回表达式的值。
>>>x = 7
>>> eval( '3 * x' )
21
>>> eval('pow(2,2)')
4
>>> eval('2 + 2')
4
>>> n=81
>>> eval("n + 4")
85
eval
函数就是实现list
、dict
、tuple
与str
之间的转化
str
函数把list
,dict
,tuple
转为为字符串
字符串转换成列表
>>> a = "[[1,2], [3,4], [5,6], [7,8], [9,0]]"
>>> print(type(a))
<type 'str'>
>>> b = eval(a)
>>> print(b)
[[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]]
字符串转换成字典
>>> a = "{1: 'a', 2: 'b'}"
>>> print(type(a))
<type 'str'>
>>> b = eval(a)
>>> print(type(b))
<type 'dict'>
>>> print(b)
{1: 'a', 2: 'b'}
字符串转换成元组
>>> a = "([1,2], [3,4], [5,6], [7,8], (9,0))"
>>> print(type(a))
<type 'str'>
>>> b=eval(a)
>>> print(type(b))
<type 'tuple'>
>>> print(b)
([1, 2], [3, 4], [5, 6], [7, 8], (9, 0))
网友评论