Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python For loop get index [duplicate]

I am writing a simple Python for loop to prnt the current character in a string. However, I could not get the index of the character. Here is what I have, does anyone know a good way to get the current index of the character in the loop?

 loopme = 'THIS IS A VERY LONG STRING WITH MANY MANY WORDS!'   for w  in loopme:     print "CURRENT WORD IS " + w + " AT CHARACTER "  
like image 986
user1817081 Avatar asked Mar 28 '13 14:03

user1817081


People also ask

How do you find the duplicate index in Python?

Method #1 : Using loop + set() In this, we just insert all the elements in set and then compare each element's existence in actual list. If it's the second occurrence or more, then index is added in result list.

How do you find the index of duplicate elements in an array?

indexOf() function. The idea is to compare the index of all items in an array with an index of their first occurrence. If both indices don't match for any item in the array, you can say that the current item is duplicated. To return a new array with duplicates, use the filter() method.


1 Answers

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  
like image 52
Martijn Pieters Avatar answered Sep 23 '22 06:09

Martijn Pieters