Search code examples
pythonindex-error

How To Fix String Index Out of Range in Python


I'm currently learning python. There is an exercise in the book which outlines code for decoding. I followed along with this code however I keep getting back an error in the middle of the program.

Here is the code that is causing the problem:

def decode(string_for_decoding):
    result = ""
    for i in range(0, len(string_for_decoding)):
        if string_for_decoding[i+1].isdigit():
            result += string_for_decoding[i] * int(string_for_decoding[i+1])
        elif string_for_decoding[i].isalpha():
            result += string_for_decoding[i]
    return result


string_for_decoding = input("Enter a string to decode: ")
print(decode(string_for_decoding))

Solution

  • Check if the index from range is larger than the number of chars in the string. It might look like this:

    def decode(string_for_decoding: str):
        result = ""
        for i in range(0, len(string_for_decoding)):
            if len(string_for_decoding) > i + 1 and string_for_decoding[i + 1].isdigit():
                result += string_for_decoding[i] * int(string_for_decoding[i + 1])
            elif string_for_decoding.isalpha():
                result += string_for_decoding[i]
        return result
    
    print(decode(input("Enter a string to decode: ")))