eval SyntaxError:python 中的语法无效

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22558548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:09:53  来源:igfitidea点击:

eval SyntaxError: invalid syntax in python

python

提问by coder_view

I want to assign :

我想分配:

x0='123'    
x1='123'    
x2='123'    
x3='123'    
x4='123'    
x5='123'    
x6='123'    
x7='123'    
x8='123'    
x9='123'    

I write the code to express that i can get the output of a string 123when input x1or x8.

我写代码是为了表示我可以123在输入x1x8.

for i in range(0,10):
    eval("x"+str(i)+"='123'")

Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "<string>", line 1
  x0='123'
  ^
SyntaxError: invalid syntax

How i can do that way?

我怎么能这样做?

采纳答案by suhailvs

For dynamic execution of statements use execstatement.

对于语句的动态执行使用exec语句。

>>> exec('y=3')
>>> y
3

Eval Usgae:eval(expression)

埃瓦尔·乌斯盖:eval(expression)

The expressionargument is parsed and evaluated as a Python expression

expression参数被解析和评价为Python表达式

eg:

例如:

>>> s=3
>>> eval('s==3')
True
>>> eval('s + 1')
4
>>> eval('s')
3
>>> eval('str(s)+"test"')
'3test'

回答by Martijn Pieters

eval()only allows for expressions. Assignment is not an expression but a statement; you'd have to use execinstead.

eval()只允许表达式。赋值不是表达式而是语句;你必须exec改用。

Even then you could use the globals()dictionary to add names to the global namespace and you'd not need to use any arbitrary expression execution.

即使这样,您也可以使用globals()字典将名称添加到全局命名空间,并且您不需要使用任何任意表达式执行。

You reallydon't want to do this, you need to keep data out of your variable namesand use a list or dictionary instead:

真的不想这样做,您需要将数据保留在变量名称之外,而是使用列表或字典:

x = ['123'] * 10

would give you a list you can address as x[0], x[1], etc. without having to execute arbitrary expressions.

会给你一个列表,你可以作为解决x[0]x[1]等等,而无需执行任意表达式。

回答by user3164787

You can you this expression.

你可以你这个表情。

eval('"x"+str(i)+"="+"123"')