首页 > 解决方案 > 如何在 Python 中修复字符串索引超出范围异常

问题描述

我的 python 代码有一些问题。我正在制作一个程序来查找单词中出现的字母A,如果找到该字母并且下一个字母不是该字母A,则将A其与下一个字母交换。

作为一个例子,TANTNA保持WHOA原样WHOA AARDVARKARADVRAK

问题是当我输入时,ABRACADABRA我得到一个字符串索引超出范围异常。在我遇到那个异常之前,我有一个打印它的词,因为 BRACADABR我不确定为什么我必须在我的程序中添加另一个循环。

如果你们还有更有效的方式来运行代码,那么我的方式请告诉我!

def scrambleWord(userInput):
    count = 0
    scramble = ''
    while count < len(userInput):
        if userInput[count] =='A' and userInput[count+1] != 'A':
            scramble+= userInput[count+1] + userInput[count] 
            count+=2
        elif userInput[count] != 'A':
            scramble += userInput[count]
            count+=1
    if count < len(userInput):
       scramble += userInput(len(userInput)-1)
    return scramble


        #if a is found switch the next letter index with a's index
def main():
    userInput = input("Enter a word: ")
    finish = scrambleWord(userInput.upper())
    print(finish)
main()

标签: pythonstringindexoutofbounds

解决方案


当您到达字符串的末尾并且它是一个“A”时,您的程序就会询问字符串末尾之外的下一个字符。

更改循环,使其不包含最后一个字符:

while count < len(userInput)-1:
    if ...

推荐阅读