我正在尝试将字符串变量极其简单地传递到我的 eval
语句中。但是,我的字符串被视为 undefined variable 。
这是我的代码:
condition = 'hi'
print(eval("2 + 4 * len(%s)" % (condition)))
输出:
Traceback (most recent call last):
File "C:\test.py", line 3, in <module>
print(eval("4 + 3 * len(%s)" % (condition)))
File "<string>", line 1, in <module>
NameError: name 'hi' is not defined
<小时/>
但是,当我将 hi
定义为变量时,代码突然编译并运行:
condition = 'hi'
hi = 'hi'
print(eval("2 + 4 * len(%s)" % (condition)))
输出:
10
这到底是怎么回事?这对我来说似乎完全不直观。有人可以帮我定义 condition
吗?Python 不要求定义 'hi'
吗?
最佳答案
%s 将被替换为 hi
。所以你要求 python 运行代码:
eval("2 + 4 * len(hi)")
len(hi)
将查找名为“hi”的变量。您想要的是 len('hi')
或 len(condition)
。以下是一些可行的替代方案:
# Simplest
print(eval("2 + 4 * len(condition)"))
# Repr gives you the string representation of the object, including quotes
print(eval("2 + 4 * len(%s)" % (repr(condition))))
# Assuming condition doesn't contain '
print(eval("2 + 4 * len('%s')" % (condition)))
关于python - 字符串在 `eval` 语句中被视为变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55556297/