繁体   English   中英

如何修复 Python 中的字符串索引超出范围异常

[英]How to fix a String index out of range exception in Python

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

例如, TANTNAWHOA保持为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()

当您到达字符串的末尾并且它是一个“A”时,您的程序就会要求输入字符串末尾的下一个字符。

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

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

您可以修改您的代码如下:

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

当逻辑尝试检查A的出现并与下一个字母交换时,您没有检查条件( count < len(userInput)-1 )。 它抛出字符串索引超出范围异常。

当输入中的最后一个字符是“A”时,您的代码中就会出现问题。 这是因为您在循环中的第一个 if 尝试在上次迭代期间访问 'count + 1' 字符。 并且由于该位置没有字符,因此会出现索引错误。

最简单的解决方案是为相同的条件创建一个单独的 if 条件。 while 循环的更新片段可能如下所示 -

# while start
while count < len_: # len_ is length of input
    if count + 1 >= len_:
        break # break outta loop, copy last character

    current = inp[count]
    next_ = inp[count + 1]

    if current == 'A':
        op += ( next_ + current) # op is result
        count += 1
    else:
        op += current

     # increment counter by 1
     count += 1

# rest of the code after while is same

代码中的另一个小问题是在复制最后一个字符时(循环结束后),您应该使用 [ ] 而不是 ( ) 来引用输入字符串中的最后一个字符。

只是为了好玩 :

from functools import reduce
def main():
    word = input("Enter a word: ").lower()
    scramble = reduce((lambda x,y : x[:-1]+y+'A' \
        if (x[-1]=='a' and y!=x[-1]) \
        else x+y),word)
    print(scramble.upper())
main()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM