pythoncodewarrior

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


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!


Solution

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