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

如何在Python中获取指定单词的首字母以开发Hangman猜词游戏

Hangman游戏提取单词首字母实现方案

首先你不需要使用split()或len()方法实现需求:split()的作用是将包含分隔符的长字符串拆分为子字符串列表,仅适用于多单词文本处理;len()的作用是获取字符串长度,和提取指定位置字符无关。
单个字符串本身支持索引访问,直接取索引为0的字符即可得到首字母,修正后的实现如下:

import random

class HangmanGame:
    def __init__(self):
        # 替换为你自己的单词库
        self.ThreeWords = ["apple", "banana", "cherry", "date"]
    
    # 提取单词首字母的专用函数
    def extract_first_letter(self, word: str) -> str:
        # 边界判断:避免空字符串、首尾带空格的异常
        cleaned_word = word.strip()
        if not cleaned_word:
            return ""
        # 统一转小写适配游戏大小写不敏感的需求
        return cleaned_word[0].lower()
    
    def example(self):
        WordChoose = random.choice(self.ThreeWords)
        first_letter = self.extract_first_letter(WordChoose)
        # 你的原有判断逻辑
        if first_letter == 'a':
            print('good')
        else:
            print('bad')
            print(f"选中单词:{WordChoose},对应首字母:{first_letter}")

# 测试运行
if __name__ == "__main__":
    game = HangmanGame()
    game.example()

注意事项

  • Python中字符串索引从0开始计数,除了首字母word[0],你也可以用word[-1]直接取单词的最后一个字符
  • 若不需要兼容特殊情况,可直接简化为first_letter = WordChoose[0]调用即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 06:51:01