【问题标题】:Python error: "IndexError: string index out of range"Python 错误:“IndexError:字符串索引超出范围”
【发布时间】:2012-02-01 12:22:49
【问题描述】:

我目前正在从一本名为“绝对初学者的 Python(第三版)”的书中学习 Python。书中有一个练习,概述了刽子手游戏的代码。我跟着这段代码,但是我一直在程序中间收到一个错误。

这是导致问题的代码:

if guess in word:
    print("\nYes!", guess, "is in the word!")

    # Create a new variable (so_far) to contain the guess
    new = ""
    i = 0
    for i in range(len(word)):
        if guess == word[i]:
            new += guess
        else:
            new += so_far[i]
        so_far = new

这也是它返回的错误:

new += so_far[i]
IndexError: string index out of range

有人可以帮我解决问题所在以及我能做些什么来解决它吗?

编辑:我像这样初始化了 so_far 变量:

so_far = "-" * len(word)

【问题讨论】:

  • 这是次要的,与您的问题无关,但您不需要 i = 0。即使尚未定义 i,for 循环也会在启动时自动设置循环变量。
  • @Chad 是的,你的权利。我不记得为什么我把它卡在了:S

标签: python python-3.x


【解决方案1】:

您似乎对so_far = new 缩进太多了。试试这个:

if guess in word:
    print("\nYes!", guess, "is in the word!")

    # Create a new variable (so_far) to contain the guess
    new = ""
    i = 0
    for i in range(len(word)):
        if guess == word[i]:
            new += guess
        else:
            new += so_far[i]
    so_far = new # unindented this

【讨论】:

  • 是的,非常感谢!我发现只对我习惯用大括号括起来的东西缩进有点令人困惑!
【解决方案2】:

您正在遍历一个字符串 (word),但随后使用其中的索引在 so_far 中查找一个字符。不能保证这两个字符串的长度相同。

【讨论】:

    【解决方案3】:

    当猜测的数量(so_far)小于单词的长度时会发生此错误。您是否在某处错过了变量 so_far 的初始化,将其设置为类似

    so_far = " " * len(word)
    

    ?

    编辑:

    试试类似的东西

    print "%d / %d" % (new, so_far)
    

    在引发错误的行之前,这样您就可以准确地看到哪里出了问题。我唯一能想到的是 so_far 在不同的范围内,你实际上并没有使用你认为的实例。

    【讨论】:

    • 对不起,我应该包括这个但忘记了。我已经以相同的方式初始化了该变量 so_far = "-" * len(word)
    • 编辑了我的回复,添加了一种调试方法,以及另一个关于可能出现问题的建议。
    • 看起来@Rob Wouters 明白了,我错过了。他是对的,so_far 应该在 for 块之外:)
    【解决方案4】:

    您的代码中有几个问题。 这里有一个可以分析的功能版本(让我们将 'hello' 设置为目标词):

    word = 'hello'
    so_far = "-" * len(word)       # Create variable so_far to contain the current guess
    
    while word != so_far:          # if still not complete
        print(so_far)
        guess = input('>> ')       # get a char guess
    
        if guess in word:
            print("\nYes!", guess, "is in the word!")
    
            new = ""
            for i in range(len(word)):  
                if guess == word[i]:
                    new += guess        # fill the position with new value
                else:
                    new += so_far[i]    # same value as before
            so_far = new
        else:
            print("try_again")
    
    print('finish')
    

    我尝试用 py2k ide 为 py3k 编写它,小心错误。

    【讨论】:

    • 是的,我只拿出一小段代码来说明问题。感谢您指出这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-23
    • 2021-01-30
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    相关资源
    最近更新 更多