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

时间:2021-04-24 16:40:19

I'm currently learning python from a book called 'Python for the absolute beginner (third edition)'. There is an exercise in the book which outlines code for a hangman game. I followed along with this code however I keep getting back an error in the middle of the program.

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

Here is the code that is causing the problem:

以下是导致问题的代码:

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

This is also the error it returns:

这也是它返回的错误:

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

Could someone help me out with what is going wrong and what I can do to fix it?

有人能帮我解决问题吗?

edit: I initialised the so_far variable like so:

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

so_far = "-" * len(word)

4 个解决方案

#1


11  

It looks like you indented so_far = new too much. Try this:

看起来你缩进了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

#2


5  

You are iterating over one string (word), but then using the index into that to look up a character in so_far. There is no guarantee that these two strings have the same length.

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

#3


2  

This error would happen when the number of guesses (so_far) is less than the length of the word. Did you miss an initialization for the variable so_far somewhere, that sets it to something like

当猜测次数(so_far)小于单词的长度时,就会发生此错误。你是否错过了对变量so_far的初始化,它将它设置为类似的

so_far = " " * len(word)

?

吗?

Edit:

编辑:

try something like

试着像

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

before the line that throws the error, so you can see exactly what goes wrong. The only thing I can think of is that so_far is in a different scope, and you're not actually using the instance you think.

在抛出错误的那行之前,你可以准确地看到哪里出错了。我能想到的唯一一件事是,so_far在不同的范围内,而您实际上并没有使用您认为的实例。

#4


0  

There were several problems in your code. Here you have a functional version you can analyze (Lets set 'hello' as the target word):

您的代码中有几个问题。这里有一个功能版本,可以进行分析(我们将“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')

I tried to write it for py3k with a py2k ide, be careful with errors.

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

#1


11  

It looks like you indented so_far = new too much. Try this:

看起来你缩进了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

#2


5  

You are iterating over one string (word), but then using the index into that to look up a character in so_far. There is no guarantee that these two strings have the same length.

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

#3


2  

This error would happen when the number of guesses (so_far) is less than the length of the word. Did you miss an initialization for the variable so_far somewhere, that sets it to something like

当猜测次数(so_far)小于单词的长度时,就会发生此错误。你是否错过了对变量so_far的初始化,它将它设置为类似的

so_far = " " * len(word)

?

吗?

Edit:

编辑:

try something like

试着像

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

before the line that throws the error, so you can see exactly what goes wrong. The only thing I can think of is that so_far is in a different scope, and you're not actually using the instance you think.

在抛出错误的那行之前,你可以准确地看到哪里出错了。我能想到的唯一一件事是,so_far在不同的范围内,而您实际上并没有使用您认为的实例。

#4


0  

There were several problems in your code. Here you have a functional version you can analyze (Lets set 'hello' as the target word):

您的代码中有几个问题。这里有一个功能版本,可以进行分析(我们将“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')

I tried to write it for py3k with a py2k ide, be careful with errors.

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