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

2024-04-27 00:28:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在从一本叫做《面向绝对初学者的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)

Tags: the代码innewlenifso面向
3条回答

当猜测的次数(目前为止)小于单词的长度时,将发生此错误。您是否在某个地方遗漏了变量的初始化,该初始化设置为

so_far = " " * len(word)

是吗?

编辑:

试试像这样的

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

在抛出错误的行之前,这样您就可以准确地看到出错的地方。我能想到的唯一一件事是,到目前为止,你还处在一个不同的范围内,你实际上并没有使用你所认为的实例。

看起来你缩进了太多。试试这个:

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

您正在对一个字符串(word)进行迭代,然后使用该字符串的索引在so_far中查找字符。不能保证这两个字符串具有相同的长度。

相关问题 更多 >