python中eval函式的用法

2021-08-30 14:00:30 字數 776 閱讀 2830

eval函式是將字串轉化為list、dict、tuple,但是字串裡的字元必須是標準的格式,不然會出錯。

str="[1,3,'hello','1314hs']"

p=eval(str)#字元裡面必須是列**式

print(type(str))

print(type(p))

print("字串轉列表:",p)

結果:

str="([6,3],[6,5],(7,9))"

p=eval(str)#字元裡面必須是元組格式

print(type(str))

print(type(p))

print("字串轉元祖:",p)

結果:

str=""

p=eval(str)#字元裡面必須是字典格式

print(type(str))

print(type(p))

print("字串轉字典:",p)

結果:

python中的eval函式

eval 函式用來執行乙個字串表示式,並返回表示式的值。還可以把字串轉化為list tuple dict。eval函式的語法 eval expression globals locals 引數 expression 表示式。globals 變數作用域,如果被提供,必須是乙個字典物件。locals 變...

Python中的eval函式

一 簡介 eval函式就是實現list dict tuple與str之間的轉化,而str函式實現把list dict tuple轉換成字串 1 字串轉化為列表 1 字串轉化為列表 2 a 1,2 3,4 5,6 7,8 9,10 3 print type a 4 b eval a 5print ty...

Python中的eval 函式

python中的eval 函式eval expression,globals none,locals none 官方文件中的解釋是,將字串str當成有效的表示式來求值並返回計算結果。globals和locals引數是可選的,如果提供了globals引數,那麼它必須是dictionary型別 如果提供...