简体   繁体   English

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

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

There is some issue with my python code.我的python代码有问题。 I am making a program that finds the occurrences of the letter A in a word and if that letter is found and the next letter is not the letter A the A is swapped with the next letter.我正在制作一个程序,用于查找单词中字母A的出现次数,如果找到该字母并且下一个字母不是字母A则将A与下一个字母交换。

As an example TAN being TNA but WHOA staying as WHOA AARDVARK being ARADVRAK例如, TANTNAWHOA保持为WHOA AARDVARKARADVRAK

The issue is when I input ABRACADABRA I get a string index out of range exception.问题是当我输入ABRACADABRA我得到一个字符串索引超出范围异常。 Before I had that exception I had the word that prints it as BRACADABR Ii'm not sure why if I have to add another loop in my program.在我遇到那个例外之前,我有一个词将它打印为BRACADABR我不知道为什么我必须在我的程序中添加另一个循环。

If you guys also have anymore efficient way to run the code then the way I have please let me know!如果你们还有更有效的方式来运行代码,那么我的方式请告诉我!

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

When you get to the end of the string and it is an 'A' your program is then asking for the next character which is off the end of the string.当您到达字符串的末尾并且它是一个“A”时,您的程序就会要求输入字符串末尾的下一个字符。

Change the loop so it doesn't include the last character:更改循环,使其不包含最后一个字符:

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

You can modify your code as below:您可以修改您的代码如下:

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

You are not checking the condition ( count < len(userInput)-1 ) when logic tries to check for A 's occurrence and swap with next letter.当逻辑尝试检查A的出现并与下一个字母交换时,您没有检查条件( count < len(userInput)-1 )。 It throws string index out of range exception.它抛出字符串索引超出范围异常。

The issue arises in your code when last character in input is 'A'.当输入中的最后一个字符是“A”时,您的代码中就会出现问题。 This is because your first if in the loop tries to access 'count + 1' character during last iteration.这是因为您在循环中的第一个 if 尝试在上次迭代期间访问 'count + 1' 字符。 And since there's no character at that position, you get index error.并且由于该位置没有字符,因此会出现索引错误。

The simplest solution would be to make a separate if condition for the same.最简单的解决方案是为相同的条件创建一个单独的 if 条件。 Updated snippet for while loop might look like this - 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

Another small issue in your code is while copying last character ( after loop ends ), you should use [ ] instead of ( ) to refer last character in input string.代码中的另一个小问题是在复制最后一个字符时(循环结束后),您应该使用 [ ] 而不是 ( ) 来引用输入字符串中的最后一个字符。

Just for fun :只是为了好玩 :

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