Python 刽子手换字逻辑

Python 刽子手换字逻辑,python,arrays,python-3.x,list,Python,Arrays,Python 3.x,List,我希望每当玩家猜到它被替换为选中的单词时,正确的角色就会替换明星 如果单词是“ton”,它将显示如下***如果玩家猜的是(t),所选单词将变成(t**),依此类推 简单语法更可取,因为我是python新手在python中不能更改字符串,它们是不可变的。改为使用列表 用列表(字符串)将所选单词更改为列表,并在相应索引处替换/更改它们。要打印,只需使用“”。join(list)创建一个新字符串,以便很好地打印它 此外,您还出现了一个错误,您将其与所选的工作进行了比较,这些工作都是*,而不是实际的字母

我希望每当玩家猜到它被替换为选中的单词时,正确的角色就会替换明星 如果单词是“ton”,它将显示如下***如果玩家猜的是(t),所选单词将变成(t**),依此类推
简单语法更可取,因为我是python新手

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

列表(字符串)
所选单词
更改为
列表
,并在相应索引处替换/更改它们。要打印,只需使用
“”。join(list)
创建一个新字符串,以便很好地打印它

此外,您还出现了一个错误,您将其与所选的工作进行了比较,这些工作都是
*
,而不是实际的字母,因此除非您输入
*
,否则您将永远无法找到匹配项

下面是完整的示例:

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

你有什么问题吗?@ForceBru很抱歉让人困惑,但我尽力描述了这个问题,如何在每次猜测正确时用字符替换星号?问题的一部分自然属于它自己的函数--将所选单词和猜测的字母作为输入,并返回要显示为输出的字符串。编写、测试和调试该函数,然后使用它。试图在不使用任何函数的情况下执行一个刽子手游戏会导致代码无法读取。至于如何做,只需在对所选单词进行迭代的同时构建字符串。
selected_list=[“*”for u in computer]
selected_list=[“*”for u in range(len(computer))]
将是更直接的创建列表的方法,而无需首先创建通过加入星号列表创建的单词。另外,
attm==attm
在定义上是正确的,但不用于任何东西,我还建议OP将其删除。您还需要将attm>0:时的
更改为
时的所选单词中的“*”和attm>0:
。否则,即使在用户猜到正确的单词后,while循环仍会继续。我不知道要使用哪些变量作为获胜的条件,两个变量必须相等,即计算机和另一个变量,您添加的for循环包含许多新语法,这就是我感到困惑的原因我没有在代码中添加太多更改,我刚才给你演示了如何正确地替换单词中的星号。我也试着采纳以前评论中的一些建议,但我把重点放在了你的问题上,那就是如何替换星号。@FirasChebil获胜的条件在底部(我添加了它)。如果while循环退出,那么您还有剩余的尝试,您就赢了。如果它因为您不再尝试而退出,则您将失败。
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