code to check the characteristics between two letters

Viewed 15

Here is the code written by me to check if there are exactly 3 characters between the letters 'a' and 'b' in the string. I have tried the code with the following three strings:

  1. 'La Rob'
  2. 'lake boat'
  3. 'look after baby'

The code worked for the first 2 strings, output: True. However, the third one is saying: IndexError: string index out of range. Instead, the third string should cause two output: False. I know why is it saying that but can not fix it, what can be a solution here to fix it ?

def hi_coder(string):
    for i in range(len(string)):
        if string[i] == 'a' and string[i+4] == 'b':
            return True
    return False
    return string        
print(hi_coder(input()))
1 Answers

If you change the upper limit for the range you won't run into trouble with Error. If you found an 'a' at the end of the string it makes no sense to look four characters further as it is the end of the string and there are no more characters there.

def hi_coder(string):
    for i in range(len(string)-4): # <<< CHANGED 
        if string[i] == 'a' and string[i+4] == 'b':
            return True
    return False
    return string        
print(hi_coder(input()))
Related