首页 > 解决方案 > 刽子手替换字符逻辑

问题描述

import random
import sys
words=["tumble","sigh","correction","scramble","building","couple","ton"]
computer=random.choice(words)
attm=7
chosen_word=len(computer)*"*"

print(chosen_word)
while attm>0:
    print(computer)
    print(chosen_word)
    player_guess=str(input("guess: "))
    if len(player_guess)>1:
        player_guess=str(input("enter one character only: "))
    if player_guess in computer:
        print("you're right")
        attm==attm
        for i in chosen_word:    
            player_guess=chosen_word.replace(chosen_word,player_guess)
            print(chosen_word)
    else:
        print("wrong!")
        attm-=1
        
    print("attempts= ",attm)
       
    
        
         
if attm==0:
    print("you lost")
    sys.exit

我希望每当玩家猜测它被替换为 selected_word 时,如果单词是“ton”,则正确的字符替换星号,如果玩家猜测是 (t),它将显示如下 *** 如果玩家猜测是 (t),则所选单词变为 (t* *) 等等简单的语法更可取,因为我是 python 新手

标签: pythonarrayspython-3.xlist

解决方案


您不能在 python 中更改字符串,它们是不可变的。而是使用列表。

将 更改chosen_word为 a listlist(string)并在相应的索引处替换/更改它们。要打印,只需使用"".join(list)创建一个新字符串即可很好地打印它。

此外,您遇到了一个错误,您将其与所选的 wors 进行了比较,这全部*而不是实际的字母,因此除非您输入 ,否则您将永远找不到匹配项*

这里是完整的例子:

import random
import sys
words = ["tumble","sigh","correction","scramble","building","couple","ton"]
computer = random.choice(words)
attm = 7
chosen_word = ["*" for i in range(len(computer))]

while "*" in chosen_word and attm > 0:    
    print(computer)
    print("".join(chosen_word))
    player_guess = str(input("guess: "))[0] # take only the first character
    if player_guess in computer:
        print("you're right")
        for idx, ch in enumerate(computer):
            if player_guess == ch:
                chosen_word[idx] = ch
        print("".join(chosen_word))
    else:
        print("wrong!")
        attm -= 1
        
    print("attempts: ",attm)
       
    
        
if attm > 0:
    print("You won!")      
else:
    print("You lost")
sys.exit

推荐阅读