You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python开发Hangman游戏触发TypeError:字符串索引需为整数而非字符串

Hangman游戏TypeError错误修复方案

错误原因

错误出现在猜中字母时的这行代码:guessword[guess] = word[guess]。guess是用户输入的字符串(比如"b"),但列表(guessword)和字符串(word)的索引必须是整数,不能用字符串作为索引,这直接触发了TypeError。

修复后的完整代码

import requests

def startgame():
    response = requests.get('https://random-word-api.herokuapp.com/word')
    word = response.json()[0]
    print(f"目标单词长度: {len(word)}")

    guessword = ['_'] * len(word)
    print(' '.join(guessword))

    while guessword != list(word):
        guess = input('Guess a letter: ').lower()
        
        # 验证输入是否为单个字母
        if len(guess) != 1 or not guess.isalpha():
            print('无效输入,请输入单个字母!')
            continue
        
        if guess in word:
            # 遍历所有匹配位置,用整数索引替换下划线
            for idx, char in enumerate(word):
                if char == guess:
                    guessword[idx] = guess
            print(f"猜对了!字母 {guess} 在单词中")
            print(' '.join(guessword))
        else:
            print("猜错了,再试试!")
        
        # 检查是否完成游戏
        if '_' not in guessword:
            print(f"\n恭喜你赢了!单词是: {''.join(guessword)}")
            break

startgame()

关键修改说明

  • 修复索引错误:使用enumerate遍历单词的索引和字符,找到所有匹配guess的位置,通过整数索引idx修改guessword,彻底避免字符串索引的问题。
  • 优化输入验证:原代码的isinstance(guess, str)判断无效(input()返回值永远是字符串),改为检查输入是否是单个字母,更符合游戏逻辑。
  • 修正胜利判断:原代码用"-" not in guessword是错误的,改为检查_是否存在,匹配初始化的占位符。
  • 提升显示体验:用' '.join(guessword)将占位符/字母用空格分隔,更符合Hangman游戏的常规显示方式。

内容的提问来源于stack exchange,提问作者CleverBeaver

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.11 13:03:21