为什么Python的eval()拒绝这个多行字符串,我如何修复它?
16lz
2021-01-22
I am attempting to eval the following tab-indented string:
我正在尝试计算下面的表缩进字符串:
'''for index in range(10):
os.system("echo " + str(index) + "")
'''
I get, "There was an error: invalid syntax , line 1"
我得到"有一个错误,无效语法,第1行"
What is it complaining about? Do I need to indent to match the eval() statement, or write it to a string file or temp file and execute that, or something else?
它在抱怨什么?我是否需要缩进来匹配eval()语句,或者将它写到字符串文件或临时文件中并执行它,或者其他什么?
Thanks,
谢谢,
4 个解决方案
#1
20
eval
evaluates stuff like 5+3
eval的值是5+3
exec
executes stuff like for ...
exec执行诸如…
>>> eval("for x in range(3):print x")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1
for x in range(3):print x
^
SyntaxError: invalid syntax
>>> exec("for x in range(3):print x")
0
1
2
>>> eval('5+3')
8
更多相关文章
- 详解Python中的from..import绝对导入语句
- python 中 字符串转换为数组,字典或表达式
- 返回语句是否应该有括号?
- Python多行正则表达式忽略字符串中的n行
- Python:内联if语句别无效
- 简单的python爬取网页字符串内容并保存
- 你怎么检查python字符串是否只包含数字?
- Python - 去除字符串首尾填充
- Python处理字符串