Issue
When I call print
from 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]')
it gives an error:
print "#{0:01d}".format(i+1), myList[i]
^
SyntaxError: invalid syntax
I tried to make use of this, and re-wrote it:
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]')
but this complains about the i
:
NameError: name 'i' is not defined
P.S. I'm dealing with python2.6
Solution
You don't need 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
or, as @SvenMarnach noted, you can put even the formatting parameter into one format call:
def printList(myList):
maxDigits = len(str(len(myList)))
for i, elem in enumerate(myList, 1):
print '#{1:0{0}} {2}'.format(maxDigits, i, elem)
Answered By - eumiro
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.