1

Coming from other languages, I know how to compare string indices to test for equality. But in Python I get the following error when trying to compare indices within a string.

TypeError: string indices must be integers

How can the indices of a string be compared for equality?

program.py

myString = 'aabccddde'
for i in myString:
    if myString[i] == myString[i + 1]:
        print('match')
crayden
  • 2,130
  • 6
  • 36
  • 65

4 Answers4

2

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.

timgeb
  • 76,762
  • 20
  • 123
  • 145
1

In this phrase:

for i in myString:

You are iterating over single letters. So myString[i] means 'aabccddde'["a"] in the first iteration, what is of course not possible.

If you would like to save order of letters and letters, you may use "enumerate" or "len":

myString = 'aabccddde'
for i in range(len(myString)-2):
    if myString[i] == myString[i + 1]:
        print('match')
Christian König
  • 3,437
  • 16
  • 28
artona
  • 1,086
  • 8
  • 13
0

You can use enumerate:

myString = 'aabccddde'
l = len(myString)
for i,j in enumerate(myString):
    if i == l-1:    # This if block will prevent the error message for last index
        break
    if myString[i] == myString[i + 1]:
        print('match')
Sociopath
  • 13,068
  • 19
  • 47
  • 75
0

Enumerate will help iterate over each character and the index of the character in the string:

myString = 'aabccddde'
for idx, char in enumerate(myString, ):
    # guard against IndexError
    if idx+1 == len(myString):
        break
    if char == myString[idx + 1]:
        print('match')
datawrestler
  • 1,527
  • 15
  • 17