Reputation: 5
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
Upvotes: 0
Views: 232
Reputation: 2881
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')
Upvotes: 1
Reputation: 3587
The index start at 0, not 1.
Try changing:
wordletter = word[num-1]
Upvotes: -1
Reputation: 1343
Because the index of the string starts at zero, the highest valid index will be wordlen-1.
Upvotes: 0
Reputation: 44112
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.
Python stdlib collections
provides excellent Counter
:
>>> from collections import Counter
>>> Counter("banana").get("x", 0)
0
>>> Counter("banana").get("a", 0)
3
Upvotes: 1
Reputation: 1121972
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.
Upvotes: 3