Waqar Ahmed
Waqar Ahmed

Reputation: 13

Why is it coming up with "IndexError: string index out of range"?

I am trying to calculate the no of times each character comes in the sentence.

message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
c = 0
for  i in message:
   a=0
   for a in range(len(message) + 1):
    if i == message[a]:
     c+=1
   print(str(i)+ ' comes ' + str(c) + ' times.')
   c=0

Upvotes: 0

Views: 29

Answers (2)

blhsing
blhsing

Reputation: 106618

Strings in Python have a starting index of 0, so when you iterate an index over the length of the string plus one with range(len(message) + 1), you would end up exceeding the the last index of the string when the index becomes len(message). Change it to range(len(message)) instead and the code would work.

Upvotes: 0

John Gordon
John Gordon

Reputation: 33335

for a in range(len(message) + 1):

If you have a message with five characters, the valid indexes are [0] through [4], but this loop will keep going to [5], which is out of range.

Take out the + 1 from your range.

Upvotes: 1

Related Questions