Python函数系列之eval()

1.作用:将字符串str当成有效的表达式来求值并返回计算结果。

 2.语法:eval(source[, globals[, locals]]) 

 3.说明:参数:source:一个Python表达式或函数compile()返回的代码对象;globals:可选。必须是dictionary;locals:可选。任意map对象。

 1 #################################################
 2 字符串转换成列表
 3 >>>a = "[[1,2], [3,4], [5,6], [7,8], [9,0]]"
 4 >>>type(a)
 5 <type 'str'>
 6 >>> b = eval(a)
 7 >>> print b
 8 [[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]]
 9 >>> type(b)
10 <type 'list'>
11 #################################################
12 字符串转换成字典
13 >>> a = "{1: 'a', 2: 'b'}"
14 >>> type(a)
15 <type 'str'>
16 >>> b = eval(a)
17 >>> print b
18 {1: 'a', 2: 'b'}
19 >>> type(b)
20 <type 'dict'>
21 #################################################
22 字符串转换成元组
23 >>> a = "([1,2], [3,4], [5,6], [7,8], (9,0))"
24 >>> type(a)
25 <type 'str'>
26 >>> b = eval(a)
27 >>> print b
28 ([1, 2], [3, 4], [5, 6], [7, 8], (9, 0))
29 >>> type(b)
30 <type 'tuple'>
原文地址:https://www.cnblogs.com/yspass/p/8118978.html