|
作者博文地址:https://www.cnblogs.com/liu-shuai/ eval 功能:將字符串str當成有效的表達式來求值并返回計算結果。 語法: eval(source[, globals[, locals]]) -> value 參數: source:一個Python表達式或函數compile()返回的代碼對象 globals:可選。必須是dictionary locals:可選。任意map對象 實例展示: 1 可以把list,tuple,dict和string相互轉化。
2 #################################################
3 字符串轉換成列表
4 >>>a = "[[1,2], [3,4], [5,6], [7,8], [9,0]]"
5 >>>type(a)
6 <type 'str'>
7 >>> b = eval(a)
8 >>> print b
9 [[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]]
10 >>> type(b)
11 <type 'list'>
12 #################################################
13 字符串轉換成字典
14 >>> a = "{1: 'a', 2: 'b'}"
15 >>> type(a)
16 <type 'str'>
17 >>> b = eval(a)
18 >>> print b
19 {1: 'a', 2: 'b'}
20 >>> type(b)
21 <type 'dict'>
22 #################################################
23 字符串轉換成元組
24 >>> a = "([1,2], [3,4], [5,6], [7,8], (9,0))"
25 >>> type(a)
26 <type 'str'>
27 >>> b = eval(a)
28 >>> print b
29 ([1, 2], [3, 4], [5, 6], [7, 8], (9, 0))
30 >>> type(b)
31 <type 'tuple'>
|
|
|