簡體   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