63

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 " 
user1817081
  • 1,185
  • 3
  • 15
  • 21

2 Answers2

110

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 
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • so with the enumerate() function, you need to define two variables? one for the index and one for the characters? – user1817081 Mar 28 '13 at 14:39
  • 2
    @user1817081: You don't *have* to; you are now looping over something that yields two-value tuples. Using tuple unpacking just makes it easier to 'receive' them. – Martijn Pieters Mar 28 '13 at 14:40
  • 3
    @user1817081: You can also do `for elem in enumerate(loopme)`, then use `elem[[0]` for the index value and `elem[1]` for the character, but that is just more cumbersome. – Martijn Pieters Mar 28 '13 at 14:41
  • Gotcha, so enumerate() is creating a map of the string. I am guessing this will also apply to a List? – user1817081 Mar 28 '13 at 14:44
  • 3
    @user1817081: `enumerate()` can be used on *any* sequence. It doesn't create a map, it simply keeps a counter. Every time the `for` construct asks for the next element, it in turn asks the wrapped sequence for the next item, then returns the value of the counter together with that next value from the wrapped sequence, then increments the internal counter. – Martijn Pieters Mar 28 '13 at 14:46
5

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
glglgl
  • 89,107
  • 13
  • 149
  • 217