I am trying to find the right way in Python to accomplish the following task (which doesn't work as written):
myList = ["a", "b", "c"]
myCounter = 5
for item in myList:
print("""Really long text
in which I need to put the next iteration of myCounter (""", myCounter++, """) followed
by a lot more text with many line breaks
followed by the next iteration of myCounter (""", myCounter++, """) followed by even
more long text until finally we get to the next
iteration of the for loop.""", sep='')
Unfortunately (for me at least), the ++ operator or statement doesn't exist in Python as a way to increment a variable by 1, but using
myCounter += 1
in its place doesn't seem work either when I want to print the variable and increment it at the same time. I want it to print 5 and 6 for the first time through the for loop, then 7 and 8 the next time through, then 9 and 10 the last time through. How should this be done in Python 3?
I might consider using itertools.count
:
import itertools
myCounter = itertools.count(5)
for item in myList:
print("la la la.", next(myCounter), "foo foo foo", next(myCounter))
If you prefer to avoid the import, you could pretty easily write your own generator to do this sort of thing as well:
def counter(val=0):
while True:
yield val
val += 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With