【问题标题】:How to fix a String index out of range exception in Python如何在 Python 中修复字符串索引超出范围异常
【发布时间】:2019-03-28 04:13:08
【问题描述】:

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

例如TANTNAWHOA 保持WHOA AARDVARKARADVRAK

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

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

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 换成A 会有什么不同吗?

标签: python stringindexoutofbounds


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

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

    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 &lt; len(userInput)-1)。它会抛出字符串索引超出范围异常。

    【讨论】:

      【解决方案3】:

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

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

      # 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
      

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

      【讨论】:

        【解决方案4】:

        只是为了好玩:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-07-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多