gpt4 book ai didi

python - 评估语法错误 : invalid syntax in python

转载 作者:太空狗 更新时间:2023-10-29 18:14:27 24 4
gpt4 key购买 nike

我要分配:

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

我写的代码表示当输入 x1x8 时我可以获得字符串 123 的输出。

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

我该怎么做?


<子> Do not ever use eval (or exec) on data that could possibly come from outside the program in any form. It is a critical security risk. You allow the author of the data to run arbitrary code on your computer.如果你来到这里是因为你想在你的 Python 程序中按照某种模式创建多个变量,你几乎肯定有一个 XY problem 。根本不要创建这些变量 - 相反,use a list or dict appropriately .

最佳答案

要动态执行语句,请使用 exec 函数:

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

eval 用法:eval(expression)

expression 参数被解析并作为 Python 表达式求值。

例如:

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

关于python - 评估语法错误 : invalid syntax in python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22558548/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com