Python:如何在循环中从 `print` 调用 `eval`?

标签 python eval python-2.x

当我从 eval 调用 print 时:

def printList(myList):
    maxDigits = len(str(len(myList)))
    Format = '0{0}d'.format(maxDigits)
    for i in myList:
        eval('print "#{0:' + Format + '}".format(i+1), myList[i]')

它给出了一个错误:

    print "#{0:01d}".format(i+1), myList[i]
        ^
SyntaxError: invalid syntax

我尝试使用 this ,并重写它:

def printList(myList):
    maxDigits = len(str(len(myList)))
    Format = '0{0}d'.format(maxDigits)
    for i in myList:
        obj = compile(src, '', 'exec')
        eval('print "#{0:' + Format + '}".format(i+1), myList[i]')

但这会提示 i:

NameError: name 'i' is not defined

附言我正在处理 python2.6

最佳答案

你不能eval()一个print:eval()是用来计算表达式的,而print是一个语句。如果要执行语句,请使用 exec()。检查this question for a better explanation :

>>> exec('print "hello world"')
hello world

现在,如果你想让 exec 中的 i 可访问,你可以传递 locals() 变量:

>>> i = 1
>>> exec('print "hello world", i', locals())
hello world 1

另外,在你写的最后一个测试中,你在'exec'模式下编译(),这应该给你一个提示:)

关于Python:如何在循环中从 `print` 调用 `eval`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9330182/

相关文章:

python - 为什么类方法的 super 需要第二个参数?

python - 使用 os.system() 在没有 root 的情况下运行命令

python - 如何使用 FirefoxProfile 或 FirefoxOptions 通过 Selenium 设置 Firefox 浏览器的窗口位置

python - 在 PyQt 上显示嵌入图像?

Javascript:使全局 eval() 的行为类似于 object.eval()

javascript - 动态创建对象,eval 的替代方法是什么?

python - Django 误解 NamedTuple

python - Windows 10 上的 Spark。 'Files\Spark\bin\..\jars"“\”未被识别为内部或外部命令

Haskell:如何评估像 "1+2"这样的字符串

python - Odoo Python3 base64 错误 : TypeError: expected bytes-like object, 不是文本