Search code examples
pythonindex-error

Cant figure out why im getting IndexError: string index out of range python


so Im working on a codesignal problem, and these are the instructions:

Given a string, your task is to replace each of its characters by the next one in the English alphabet; i.e. replace a with b, replace b with c, etc (z would be replaced by a).

Example

For inputString = "crazy", the output should be alphabeticShift(inputString) = "dsbaz".

Input/Output

[execution time limit] 4 seconds (py3)

[input] string inputString

A non-empty string consisting of lowercase English characters.

Guaranteed constraints:
1 ≤ inputString.length ≤ 1000.

[output] string

The resulting string after replacing each of its characters.

this is my code:

def alphabeticShift(inputString):
    abc = "abcdefghijklmnopqrstuvwxyza"
    newString = ""
    for letter in inputString:
        abcIndex = 0
        for abcletter in abc:
          
          if letter == abcletter:
              newString = newString+abc[abcIndex+1]
          abcIndex = abcIndex+1
    return newString

print(alphabeticShift("*_fArgs_uiutgbodsupy"))

I have tried my code in replit and it executes just fine but I keep getting this error when I put it in codesignal:

Traceback (most recent call last):

  File main.py3 in the pre-written template, in getUserOutputs
    userOutput = _rundngpj(testInputs[i])

  File main.py3 in the pre-written template, in _rundngpj
    return alphabeticShift(*_fArgs_asixuqfdhzqc)

  File main.py3 on line 10, in alphabeticShift
    newString = newString+abc[abcIndex+1]
IndexError: string index out of range

I dont know what I am missing as i dont see how anything could be out of range?


Solution

  • Add a break statement inside the if condition.

    if letter == abcletter:
        newString = newString+abc[abcIndex+1]
        break
    

    The reason it fails is when you encounter a, you are trying to replace it twice, once at the start and once in the end of abc which fails.