Python For loop get index [duplicate]
Solution 1:
Use the enumerate()
function to generate the index along with the elements of the sequence you are looping over:
for index, w in enumerate(loopme):
print "CURRENT WORD IS", w, "AT CHARACTER", index
Solution 2:
Do you want to iterate over characters or words?
For words, you'll have to split the words first, such as
for index, word in enumerate(loopme.split(" ")):
print "CURRENT WORD IS", word, "AT INDEX", index
This prints the index of the word.
For the absolute character position you'd need something like
chars = 0
for index, word in enumerate(loopme.split(" ")):
print "CURRENT WORD IS", word, "AT INDEX", index, "AND AT CHARACTER", chars
chars += len(word) + 1