Vito Vito - 2 months ago 8
Python Question

How to debug "IndexError: string index out of range" in Python?

I am trying to solve Ex. 9.6 Think Python 3.


Question: Write a function called is_abecedarian that returns True if the letters in a word appear in alphabetical order (double letters are ok). How many abecedarian words are there?


What I have written:

fin= open('words.txt')
for line in fin:
line=fin.readline()
word=line.strip()
c=0
index=0
for letter in word:
if ord(letter)<ord(word[index+1]):
c=c+1
index=index+1
if c==len(word):
print(word)


My approach is to convert letters to numeric value and match them with the next letter in the word by increasing the index by 1 each time loop ends and count each time. If count comes to be equal to the length of word that means all the times the previous letter was lesser in value than next. So print the word.

Error:

Traceback (most recent call last): File "C:\Users\KARAN\Desktop\Python\Programs\practice.py", line 8, in <module> if ord(letter)<ord(word[index+1]): IndexError: string index out of range


I am getting 'IndexError' but I don't think index that is 0+1=1 should be out of range? I tried to search it up but couldn't get my answer.

Answer

(Posted on behalf of the OP).

Final solution:

fin= open('words.txt')
for line in fin: 
    line=fin.readline()
    word=line.strip()
    c=0
    index=0
    while index!=(len(word)-1):
        i=(word[index])
        j=(word[index+1])
        index=index+1
        if ord(j)>=ord(i):
            c=c+1
    if c==(len(word)-1):
        print(word)