eval()在运行时不分配变量 [英] eval() does not assign variable at runtime

查看:96
本文介绍了eval()在运行时不分配变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用eval()将列表分配给var:

I use eval() to assign a list to a var:

eval('mylist = [1,2,3]') 

但是当我运行它时,出现了SyntaxError.它出什么问题了?如果我不能在eval()中进行赋值,如何在运行时中赋值var.

but when I run it , I got a SyntaxError. What's wrong with it? If I cannot do assignment in the eval(), how do I assign a var in the runtime.

推荐答案

对语句使用exec:

>>> exec 'lis = [1,2,3]'
>>> lis
[1, 2, 3]

eval仅适用于表达式,例如2*24+5

eval works only on expressions, like 2*2,4+5 etc

evalexec都可以,但是如果字符串来自未知来源(用户输入),则不要使用它们.

eval and exec are okay if the string is coming from a known source, but don't use them if the string is coming from an unknown source(user input).

阅读:请谨慎使用Python中的exec和eval

这篇关于eval()在运行时不分配变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆