0

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
5
  • 1
    Because the string index is out of range: why len(message) + 1? Commented Apr 19, 2019 at 20:39
  • 1
    How can range(len(message) + 1) not throw an index error? You took the length of the list of possible indices and then threw an extra one in that can't exist Commented Apr 19, 2019 at 20:41
  • 1
    Valid string indexes go from 0 to len(message) - 1, which is why range() conveniently also only goes from 0 to end - 1. So remove the + 1 in your range() statement and this will resolve your IndexError. (There are other issues with your algorithm too, but this will take care of your immediate question.) Commented Apr 19, 2019 at 20:41
  • Initialize c before use, not afterwards. Or simply c = message.count(i). Commented Apr 19, 2019 at 20:44
  • @Daniel they did initialize c before use Commented Apr 19, 2019 at 20:45

2 Answers 2

1
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.

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

Comments

0

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.

Comments

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.