2012-02-17 74 views
3

当我打电话printevalPython:如何在循环中从`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 

P.S.我处理python2.6

+0

的Python的版本?除非我误解,否则python 3中的打印语法是不同的。 – Marcin 2012-02-17 14:42:23

+6

为什么使用eval开头? – Gerrat 2012-02-17 14:43:03

+0

这是哪个版本的python? – 2012-02-17 14:43:33

回答

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) 
+4

你甚至不需要建立'str_format'。 'print“{0:0 {1}}”。format(i,maxDigits)'将会正常工作。 – 2012-02-17 15:15:47

+0

有趣的是,你的评论被投票比我的回答更好,尽管我首先发布了它:p – Gandaro 2012-02-17 18:09:50

+0

@Gandaro - 他从我那里得到了更多(你也是),因为这个嵌套对我来说是新的。 – eumiro 2012-02-17 18:22:02

8

您不能eval() a printeval()用于评估表达式,并且print是一个语句。如果要执行语句,请使用exec()。检查this question for a better explanation

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

现在,你可以通过你的当地人()的变量,如果你想访问Exec中我:

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

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

+0

恕我直言,这应该是被接受的答案:) – vks 2015-03-24 17:14:56

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] 
+0

ValueError:无效的转换规范 – Gandaro 2012-02-17 14:58:26

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]