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

Python猜字母游戏技术求助:无法实现字母替换功能

Solution for Letter Replacement in Your Python Guess-the-Letter Game

Hey there! Let's sort out that letter replacement logic you're stuck on—this is a common hangman-style game feature, and once you see how it works, it'll click right away.

Core Idea

The key here is to use a mutable data structure (like a list) to track the current visible state of the word. Strings in Python are immutable, so you can't directly change a single character in them—lists let you update specific positions easily.

Step-by-Step Implementation

Here's a complete, working example that includes the replacement logic you need:

# Get the target word from the user
target_word = input("Enter the target word: ").lower()

# Initialize the display list with asterisks (same length as target word)
display = ["*"] * len(target_word)

while True:
    # Print the current state
    print("\nSo far you have:")
    print("".join(display))
    
    # Get user's guess
    guess = input("\nEnter a letter: ").lower()
    
    # Check if the guess is in the target word
    if guess in target_word:
        # Loop through each index and character in the target word
        for idx, char in enumerate(target_word):
            if char == guess:
                # Update the display list at the matching index
                display[idx] = guess
    else:
        print(f"Oops, '{guess}' isn't in the word!")
    
    # Optional: Check if the game is won (no asterisks left)
    if "*" not in display:
        print("\nCongratulations! You guessed the word:", target_word)
        break

Key Explanations

  • display list: Starts as all asterisks, one for each character in the target word. Using a list lets us modify individual positions when a correct letter is guessed.
  • enumerate(target_word): This gives us both the index (idx) and the character (char) for each position in the target word—perfect for finding where to update the display.
  • "".join(display): Converts the list back to a string for clean printing (since lists print with brackets and commas otherwise).

Testing with Your Example

If the target word is dog:

  1. Initial display: ***
  2. User guesses a: Display stays *** with an error message
  3. User guesses o: The loop finds the index 1 (since dog[1] = 'o'), updates display[1] to o, so the display becomes *o*

This logic will also handle multiple occurrences of the same letter—if the target word was book, guessing o would update both positions 1 and 2 to o.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:32:33