Python for
loops are sometimes known as "foreach" loops in other languages. You are not looping over indices, you are looping over the characters of the string. Strings are iterable and produce their characters when iterated over.
You may find this answer and part of this answer helpful to understand how exactly a for
loop in Python works.
Regarding your actual problem, the itertools
documentation has a recipe for this called pairwise
. You can either copy-paste the function or import it from more_itertools
(which needs to be installed).
Demo:
>>> # copy recipe from itertools docs or import from more_itertools
>>> from more_itertools import pairwise
>>> myString = 'aabccddde'
>>>
>>> for char, next_char in pairwise(myString):
... if char == next_char:
... print(char, next_char, 'match')
...
a a match
c c match
d d match
d d match
In my opinion, we should avoid explicitly using indices when iterating whenever possible. Python has high level abstractions that allow you to not get sidetracked by the indices most of the time. In addition, lots of things are iterable and can't even be indexed into using integers. The above code works for any iterable being passed to pairwise
, not just strings.