python学习笔记6-Python内置函数 eval

今天继续学习 Python,做一个小案例的时候,用到了 eval 函数,挺有意思的,记录下来。

eval 功能简单来说就是:把字符串转为Python语句并执行。

语法:eval(   string [, globals[, locals] ]  )  

参数:

string:一个Python表达式 或 函数 compile() 返回的代码对象,字符串。

globals:可选。必须是dictionary

locals:可选。任意map对象

如果提供了globals参数,那么它必须是dictionary类型;如果提供了locals参数,那么它可以是任意的map对象。

感觉 globals 和 locals 用的比较少。

x = 2
y = 3
res = eval( "x**2+3") 
print(res)   # 7

eval 还有个有意思的功能就是可以把 str 转换成 list, tuple, dict 。

str1 = "[2,3,4,5]"
L = eval(str1)
print( type(L),L )    # <class 'list'> [2, 3, 4, 5]

在转换的时候,如果字符串有空格、\n 换行之类的,会被忽略掉,保证了数据的稳定性。

str1 = " [2, 3,\n4,5] \n"
L = eval(str1)
print( type(L),L )    # <class 'list'> [2, 3, 4, 5]

这点,在把数据存储为文本形式的时候超级有用。

发布了73 篇原创文章 · 获赞 97 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/weixin_42703239/article/details/104136875