当我打电话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]')
Run Code Online (Sandbox Code Playgroud)
它给出了一个错误:
print "#{0:01d}".format(i+1), myList[i]
^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)
我试着利用这个,然后重写它:
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]')
Run Code Online (Sandbox Code Playgroud)
但这抱怨i:
NameError: name 'i' is not defined
Run Code Online (Sandbox Code Playgroud)
PS我正在处理 python2.6
tit*_*ito 15
你不能eval()a print:eval()用于评估表达式,而print是一个声明.如果要执行语句,请使用exec().请查看此问题以获得更好的解释:
>>> exec('print "hello world"')
hello world
Run Code Online (Sandbox Code Playgroud)
现在,如果要在exec中使i可访问,则可以传递locals()变量:
>>> i = 1
>>> exec('print "hello world", i', locals())
hello world 1
Run Code Online (Sandbox Code Playgroud)
另外,在你写的最后一个测试中,你在'exec'模式下编译()应该给你一个提示:)
你不需要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
Run Code Online (Sandbox Code Playgroud)
或者,正如@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)
Run Code Online (Sandbox Code Playgroud)