0

Python cannot seem to differentiate between duplicates of the same letter. For example:

word = "australia"
variable = "a"
for letter in word:
    if variable == letter:
        index = word.index( letter )
        print index

The result is:

0
0
0

While python knows that there are three occurrences of the letter "a" in the word "australia", it keeps returning the index of the first occurrence. How can I fix this? Thanks.

bariox
  • 13
  • 3
  • `word.index( letter )` will always return the index of the first occurance of `a` (which is 0) even though you're calling it multiple times in a loop. – 101 Jun 01 '16 at 23:38
  • @101 yes I understand this, but how can I change my code to get it to return the index of the other two occurrences also – bariox Jun 01 '16 at 23:40
  • Check the first answer in the above link, it gives what you're after. – 101 Jun 01 '16 at 23:42
  • @bariox: do read the documentation for methods you use. [`str.index()`](https://docs.python.org/2/library/stdtypes.html#str.index) takes additional arguments, like `start`. `word.index(letter, index + 1)` would start searching from the last location. Or just *generate an index as you go along*; you have a loop, increment a counter in it. Or have Python do this for you with `enumerate()`. – Martijn Pieters Jun 01 '16 at 23:42
  • 1
    @101 Thanks I was able to implement that post into my code – bariox Jun 02 '16 at 00:02

0 Answers0