0

I keep getting an "IndexError: string index out of range" error message when I try to execute this code:

#function countLetters(word,letter) should count the number of times
#a particular letter appears in a word.

def countLetters(word, letter):

    count=0

    wordlen=len(word)
    num=0
    wordletter=""

    while(num<=wordlen):
        wordletter=word[num]
        if(wordletter==letter):
            count=count+1
        num=num+1
    return count

print(countLetters("banana", "x"))#should print 0
print(countLetters("banana", "a"))#should print 3
print(countLetters("banana", "b"))#should print 1

The Error Message:

Traceback (most recent call last):
  File "C:\Users\Charlie Chiang\Desktop\9G.py", line 17, in <module>
    print(countLetters("banana", "x"))
  File "C:\Users\Charlie Chiang\Desktop\9G.py", line 10, in countLetters
    var=word[num]
IndexError: string index out of range
4
  • The code being run and the code you are looking into, seems to me, are different. There is no var=word[num] in your source while the Traceback seems to think there is Commented Jul 16, 2014 at 22:12
  • @shaktimaan: It was close enough; instead of var it is wordletter=word[num]. Commented Jul 16, 2014 at 22:13
  • FYI, I don't know if this is for an assigment, but you can always just use .count(). Example: "banana".count("a") returns 3. Commented Jul 16, 2014 at 22:16
  • Yeah, I'm taking a class, it was an assignment. Commented Jul 16, 2014 at 22:21

5 Answers 5

3

You take it one index too far:

while(num<=wordlen):

num must stay strictly below the length:

while num < wordlen:

because Python sequences are 0-based. A string of length 5 has indices 0, 1, 2, 3, and 4, not 5.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank You so much! I feel really stupid now, but at least I know what I did wrong! I can't thank you enough, I've been trying to figure this out for the past 2 days!THANK YOU!
1

You are reaching one index too far:

while(num<=wordlen):

For a text "a" the len("a") is 1 and last letter can be reached by index 0. Your while condition allows trying index 1, which is not available.

Bonus: counting using Counter

Python stdlib collections provides excellent Counter:

>>> from collections import Counter
>>> Counter("banana").get("x", 0)
0
>>> Counter("banana").get("a", 0)
3

Comments

1

Fixing your code:

def countLetters(word, letter):

    count=0

    wordlen=len(word)
    num=0
    wordletter=""
    #here, because the index access is 0-based
    #you have to test if the num is less than, not less than or equal to length
    #last index == len(word) -1
    while(num<wordlen):
        wordletter=word[num]
        if(wordletter==letter):
            count=count+1
        num=num+1
    return count

print(countLetters("banana", "x"))#should print 0
print(countLetters("banana", "a"))#should print 3
print(countLetters("banana", "b"))#should print 1

more elegant way: str.count method

'banana'.count('x')
'banana'.count('a')
'banana'.count('b')

Comments

0

Because the index of the string starts at zero, the highest valid index will be wordlen-1.

Comments

-1

The index start at 0, not 1.

Try changing:

wordletter = word[num-1]

1 Comment

@f.rodriques The question shows code starting with index 0.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.