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

时间:2012-02-17 14:41:09

标签: python eval

当我从print致电eval时:

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

P.S。我正在处理python2.6

4 个答案:

答案 0 :(得分:14)

您不能eval() printeval()用于评估表达式,而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'模式下编译(),应该给您一个提示:)

答案 1 :(得分:7)

您不需要eval:

def printList(myList):
    maxDigits = len(str(len(myList)))
    str_format = '#{0:0' + str(maxDigits) + '}'
    for i, elem in enumerate(myList, 1):
        print str_format.format(i), elem

或者,正如@SvenMarnach所说,你甚至可以将格式化参数放到一个格式调用中:

def printList(myList):
    maxDigits = len(str(len(myList)))
    for i, elem in enumerate(myList, 1):
        print '#{1:0{0}} {2}'.format(maxDigits, i, elem)

答案 2 :(得分:3)

保持代码的同时缩短并更容易理解:

def printList(myList):
    # int(math.log10(len(myList))+1) would be the appropriate way to do that:
    maxDigits = len(str(len(myList)))
    for i in myList:
        print "#{0:0{1}d}".format(i+1, maxDigits), myList[i]

答案 3 :(得分:1)

简单化的观点就是这样。与使用它分开构建格式。避免使用eval()

    format =  "#{0:" + Format + "}"
    print format.format(i+1), myList[i]

不要让事情比他们需要的更难。这是另一个版本,可以一步构建格式。

    format = '#{{0:0{0}d}}'.format(maxDigits)
    print format.format(i+1), myList[i]