[英]Python error: “IndexError: string index out of range”
我目前正在從一本名為“絕對初學者的 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)
看起來你縮進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
您正在迭代一個字符串 ( word
),然后使用該索引在so_far
查找字符。 不能保證這兩個字符串具有相同的長度。
當猜測次數 (so_far) 小於單詞的長度時,就會發生此錯誤。 您是否在某處錯過了變量 so_far 的初始化,將其設置為類似
so_far = " " * len(word)
?
編輯:
嘗試類似
print "%d / %d" % (new, so_far)
在引發錯誤的行之前,這樣您就可以確切地看到出了什么問題。 我唯一能想到的是 so_far 在不同的范圍內,並且您實際上並沒有使用您認為的實例。
您的代碼中有幾個問題。 在這里,您有一個可以分析的功能版本(讓我們將“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')
我試圖用 py2k ide 為 py3k 編寫它,小心錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.