Home > Back-end >  A program to print "Hiss" If the input string contains two consecutive occurrences of the
A program to print "Hiss" If the input string contains two consecutive occurrences of the

Time:02-04

We need to write a piece of code to print "Hiss", If the input string contains two consecutive occurrences of the letter s and print "No hiss" if it doesn't. What I've written so far is this:

word = list(input())

for i in range(len(word)):
    if word[i] == 's':
        if word[i 1] == 's':
            print("hiss")
        else:
            print("no hiss")

The problem is that I get this error message : IndexError: list index out of range.

I think the problem is related to this part of the code word[i 1] == 's' but I can't really understand the reason, here, in this line, I'm trying to compare an item, with the next item so what is the problem and how can I fix this?

Thanks in advance

CodePudding user response:

For example, your string word looks like hiss and the length of it is 4. For is iterating from 0 to 3 and when you add 1, you're trying to access 4 element which doesn't exist (cause' index of all iterable objects starts from 0) Here you read about out of range exception

word = input()

if 'ss' in word:
   print('Yes')
else:
   print('No')

In this code you trying to find substring 'ss' in word, and if it's in in keyword will return true else return false

  • Related