当我从 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/