为什么Python的eval()拒绝此多行字符串,我该如何解决? [英] Why is Python's eval() rejecting this multiline string, and how can I fix it?

查看:645
本文介绍了为什么Python的eval()拒绝此多行字符串,我该如何解决?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试评估以下制表符缩进的字符串:

I am attempting to eval the following tab-indented string:

'''for index in range(10):
        os.system("echo " + str(index) + "")
'''

我得到出现错误:语法无效,第1行"

I get, "There was an error: invalid syntax , line 1"

它在抱怨什么?我需要缩进以匹配eval()语句,还是将其写入字符串文件或临时文件并执行,或者执行其他操作?

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对诸如5+3

exec执行类似for ...

>>> 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的eval()拒绝此多行字符串,我该如何解决?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆