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

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

所以我正在研究一个代码信号问题,这些是说明:

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.

这是我的代码:

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"))

我已经在 replit 中尝试了我的代码,它执行得很好,但是当我把它放在 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

我不知道我错过了什么,因为我没有看到任何东西可能超出范围?

在 if 条件中添加一个 break 语句。

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

它失败的原因是当你遇到 a 时,你试图替换它两次,一次在开头,一次在 abc 的结尾,但失败了。

您在找到一个字母后没有退出 for abcLetter 循环,并且 a 出现了两次。所以当letter"a"时,你添加"b",然后你继续循环,找到另一个"a"并尝试添加它后面的字母也是如此——但是有 none。附加字母后 break 将修复它。

也就是说,这里有很多不合惯用的地方,解决方案可以简单得多——例如通过使用 str.translate:

shift = str.maketrans(
  'abcdefghijklmnopqrstuvwxyz',
  'bcdefghijklmnopqrstuvwxyza',
)
def alphabeticShift(inputString):
    return inputString.translate(shift)