標籤:value eval post glob local 執行個體 官方文檔 point string
eval()函數
eval()官方文檔裡面給出來的功能解釋是:將字串string對象轉化為有效運算式參與求值運算返回計算結果
文法上:調用的是:eval(expression,globals=None, locals=None)返回的是計算結果
功能:將字串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 b19 {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 b29 ([1, 2], [3, 4], [5, 6], [7, 8], (9, 0))30 >>> type(b)31 <type ‘tuple‘>
參考:
http://www.cnblogs.com/dadadechengzi/p/6149930.html
Python學習劄記-eval函數