Python错误:"IndexError:字符串索引超出范围"

19

我目前正在从一本名为“Python for the absolute beginner (third edition)”的书中学习Python。这本书中有一个练习,其中概述了一个hangman游戏的代码。我按照这个代码进行操作,但是在程序运行中间一直收到错误。

以下是导致问题的代码:

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)

4
这只是一个小问题,并且与您的问题无关,但您不需要 i = 0。即使 i 尚未定义,for 循环也会在启动时自动设置循环变量。 - Free Monica Cellio
@Chad 是的,你说得对。我不记得当时为什么要加那个 :S - Darkphenom
4个回答

22

看起来你把 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

是的,非常感谢!我觉得仅仅使用缩进来代替我习惯用花括号包裹的东西有点令人困惑! - Darkphenom

6
您正在迭代一个字符串(word),但是接着又使用该字符串的索引来查找so_far中的字符。这两个字符串长度不一定相同。

2

如果猜测的次数(so_far)少于单词的长度,则会出现此错误。您是否忘记了在某个地方初始化变量so_far,将其设置为类似以下内容:

so_far = " " * len(word)

?

Edit:

try something like

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

在抛出错误的那一行之前,你可以看到具体出了什么问题。我唯一能想到的是,so_far处于不同的作用域,而你实际上没有使用你认为的实例。


抱歉,我应该包括这一点,但是忘了。我已经以相同的方式初始化了该变量 so_far = "-" * len(word) - Darkphenom
编辑了我的回复,添加了一种调试的方法,并提出了另一个可能出错的建议。 - CNeo
看起来@Rob Wouters已经解决了这个问题,我错过了。他是正确的,so_far应该在for块之外 :) - CNeo

1

你的代码存在几个问题。 这里有一个可用的版本,你可以分析一下(我们将“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代码,请注意错误。


是的,我只提取了一小段代码来说明重点。不过感谢你指出来。 - Darkphenom

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接