Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment integer in print statement

I have this piece of code in python 3:

i=0
for item in splitDict(Team, 3):
    i+=1
    print("{1} #{0}".format(i,item))

What I'd like to do is:

i=0
for item in splitDict(Team, 3):
    print("{1} #{0}".format(i+=1,item))

Notice I've put the increment into the format statement. But when I run it I get the error:

print("{1} #{0}".format(i+=1,item))
                              ^
SyntaxError: invalid syntax

My question is how can I get it to increment in the print statement?

like image 593
Dan Avatar asked Aug 04 '26 22:08

Dan


1 Answers

Clearly you are really wanting to use enumerate to solve your problem. But to answer the specific question of "how can I increment i within the print statement" ... then you can do the following very ugly thing (its not strictly within):

i=0
for item in splitDict(Team, 3):
    i += print("{1} #{0}".format(i + 1, item)) or 1

But you shouldn't. Use enumerate:

for i, item in enumerate(splitDict(Team, 3)):
    print("{1} #{0}".format(i, item))
like image 136
donkopotamus Avatar answered Aug 06 '26 10:08

donkopotamus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!