Receiving an exit code error on codewars when trying to manipulate a string

184 views Asked by At

Please do not include any spoilers if possible.

I'm working on Kata Exclamation marks series #1: Remove an exclamation mark from the end of string and have been receiving an IndexError: string index out of range despite my code executing properly.

The purpose of the program is to remove an exclamation mark from the end of a string if it exists.

def remove(s):
    length = len(s)
    if s[len(s)-1] == '!':
        new = slice(0,-1,)
        return(s[new])
    else:
        return(s)

The error comes up at: if s[len(s)-1] == '!':

If anyone could explain why I'm getting this error that would be much appreciated!

3

There are 3 answers

2
Charbel abi daher On BEST ANSWER

Your code crashes if you enter an empty string (you will get an IndexError.)

Moreover, it's not very pythonic and you have an unused variable. For example, you don't need the parentheses after return, and [-1] lets you directly access the last element of the string. Here's a way to write this:

def remove(s):
    if s and s[-1] == '!':
            return s[:-1]
    return s

if s will check if the input string is different than '' to make sure that the input isn't an empty string, then if checks if '!' is in there.

You could also use str.endswith() as user Boris pointed out (which I was not aware of before.)

Edit: if you need me to remove the code to not have any spoilers I gladly will, but your post itself contains an attempt at a model solution to begin with.

0
Ajay A On

Try this

def remove(s):
    return s[:-1] if s.endswith('!') else s
0
CryptoFool On

You will get that error if you call your function with an empty string, ie:

def remove(s):
    length = len(s)
    if s[len(s)-1] == '!':
        new = slice(0,-1,)
        return(s[new])
    else:
        return(s)

remove("")

Result:

Traceback (most recent call last):
  File "/Users/steve/Development/Inlet/inletfetch_if2/test/behave/features/Blah.py", line 9, in <module>
    remove("")
  File "/Users/steve/Development/Inlet/inletfetch_if2/test/behave/features/Blah.py", line 3, in remove
    if s[len(s)-1] == '!':
IndexError: string index out of range

This occurs because you're asking for the last character in the string, and since there are no characters in the string, there is no last character in the string.