我正在 Python 上进行“猜单词”,但我无法找出这个错误。
AttributeError: 'int' object has no attribute 'index' (python)
它给了我一个错误
letterIndex=word.index(guess)
。
def checkLetter(word):
blanks = '_' * len(str(word))
print('Word: ', blanks)
if str(guess) == str(letters):
letterIndex = word.index(guess)
newBlank = blanks[:letterIndex * 2] + guess + blanks[letterIndex * 2 + 1]
print('Guess Corrrect')
从之前将单词转换为字符串时开始,我认为单词不是字符串。考虑到这一点,它可能没有索引功能。至少,您可能需要将该行更改为
letterIndex=str(word).index(guess)
尽管我会提出问题,为什么名为 word 的变量是 int。
AttributeError:“int”对象没有属性“index”
错误消息再清楚不过了。它告诉您
word
是一个 int
并且没有名为 index
的属性。您想让 word
成为一根字符串吗?或者您忘记将其转换为字符串?
word
变量属于int
类型,int
类型没有index
功能。
使用 str()
: 将单词转换为字符串类型
letterIndex=str(word).index(guess)