標籤:color int log 執行個體 .com 參數 tps eval 功能
作者博文地址:https://www.cnblogs.com/liu-shuai/
eval
功能:將字串str當成有效運算式來求值並返回計算結果。
文法: eval(source[, globals[, locals]]) -> value
參數:
source:一個Python運算式或函數compile()返回的代碼對象
globals:可選。必須是dictionary
locals:可選。任意map對象
執行個體展示:
可以把list,tuple,dict和string相互轉化。#################################################字串轉換成列表>>>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‘>#################################################字串轉換成元組>>> 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 ‘tuple‘>
Python eval 函數妙用