Python错误:“IndexError:字符串索引超出范围" [英] Python error: "IndexError: string index out of range"
本文介绍了Python错误:“IndexError:字符串索引超出范围"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我目前正在从一本名为绝对初学者的 Python(第三版)"的书中学习 Python.书中有一个练习概述了刽子手游戏的代码.我跟着这个代码但是我一直在程序中间返回一个错误.
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.
这是导致问题的代码:
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
有人能帮我解决哪里出了问题以及我能做些什么来修复它吗?
Could someone help me out with what is going wrong and what I can do to fix it?
我像这样初始化了 so_far 变量:
edit: I initialised the so_far variable like so:
so_far = "-" * len(word)
推荐答案
看起来您将 so_far = new
缩进太多了.试试这个:
It looks like you indented so_far = new
too much. Try this:
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
这篇关于Python错误:“IndexError:字符串索引超出范围"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文