今天工作中看见了一段代码,其中有一个eval()
函数,没有见过,故查之。
功能:
将字符串str当成有效的表达式来求值并返回计算结果。
语法:
eval(source[, globals[, locals]]) -> value
参数:
source:一个Python表达式或函数compile()返回的代码对象
globals:可选。必须是dictionary
locals:可选。任意map对象
还有一个对应的函数,repr()
函数,
功能:
repr()
能够将Python的变量和表达式转换为字符串表示
实际用法,网上说大多用来巧妙的把str
类型准换成list
dict
等,工作中的代码,也是这么用的。
参考示例如下:
#字符串转换成列表
>>>a = "[[1,2], [3,4], [5,6], [7,8], [9,0]]"
>>>type(a)
<type 'str'>
>>> b = eval(a)
>>> print b
[[1, 2], [3, 4], [5, 6], [7, 8], [9, 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'>
至此,已经可以能看懂代码了。
点到即止