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

19 投票
4 回答
327119 浏览
提问于 2025-04-17 09:27

我现在正在学习一本叫《绝对初学者的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)

4 个回答

2

这个错误发生的原因是你猜的次数(so_far)少于单词的长度。你有没有在某个地方忘记初始化so_far这个变量,让它的值变成了类似这样的东西呢:

so_far = " " * len(word)

?

补充:

试试在抛出错误的那一行之前加上这样的代码:

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

这样你就能清楚地看到到底出了什么问题。我能想到的唯一原因是so_far在不同的作用域里,你可能并没有使用你认为的那个实例。

6

你正在遍历一个字符串(word),但接着用这个字符串的索引去查找另一个字符串so_far中的字符。这样做没有保证这两个字符串的长度是一样的。

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

撰写回答