eval() does not assign variable at runtime

a 夏天 提交于 2019-12-06 23:31:36

问题


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

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

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.


回答1:


Use exec for statements:

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

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

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).

Read : Be careful with exec and eval in Python



来源:https://stackoverflow.com/questions/17230005/eval-does-not-assign-variable-at-runtime

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!