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

Dar*_*nom 14 python python-3.x

我目前正在从一本名为"绝对初学者的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
Run Code Online (Sandbox Code Playgroud)

这也是它返回的错误:

new += so_far[i]
IndexError: string index out of range
Run Code Online (Sandbox Code Playgroud)

有人可以帮助我解决出错的问题以及我可以做些什么来解决这个问题?

编辑:我初始化了so_far变量,如下所示:

so_far = "-" * len(word)
Run Code Online (Sandbox Code Playgroud)

Rob*_*ers 14

看起来你缩进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
Run Code Online (Sandbox Code Playgroud)


unw*_*ind 5

您正在迭代一个字符串(word),但随后使用索引来查找字符so_far.无法保证这两个字符串具有相同的长度.