用单词替换字母

时间:2019-02-24 14:18:03

标签: python

如果猜测正确,则将字母替换为“-”。在for循环中,如何存储以前的结果并使用新结果进行更新?

import random

WORDS = ('linux', 'windows')
correct_word = random.choice(WORDS)


for n in range(5):
    guess = input('Enter a letter: ')
    letter = ''.join(x if x in guess else '-' for x in correct_word)

    if letter in correct_word:
        print("So far you have: ", letter)

    else:
        print("So far you have: ", letter)

4 个答案:

答案 0 :(得分:1)

尝试像这样使变量中到目前为止猜出的字母保持不变(我删除了if语句,因为两个分支都执行相同的操作)。还添加了输入验证:

import random

WORDS = ("linux", "windows")
correct_word = random.choice(WORDS)

def get_single_letter_input():
    while True:
        guess = input("Enter a letter: ")
        if len(guess) == 1:
            return guess

word_so_far = "".join("-" for letter in correct_word)
for n in range(5):
    guess = get_single_letter_input()
    word_so_far = "".join(x if x in guess else word_so_far[i]
                          for i, x in enumerate(correct_word))

    print(f"So far you have: {word_so_far}")

答案 1 :(得分:0)

您可以尝试使用re.sub进行正则表达式替换。该答案假定您可以使用correct_word本身来保持状态,可以通过为用户选择的每个匹配字母用破折号更新来保持状态。

import random

WORDS = ('linux', 'windows')
correct_word = random.choice(WORDS)

for n in range(5):
    guess = input('Enter a letter: ')

    if len(guess) > 1 or len(guess) == 0
        print("Please choose a single letter only")

    if letter in correct_word:
        print("Correct choice")
        correct_word = re.sub(guess, '-', correct_word)

    else:
        print("Letter not present")

答案 2 :(得分:0)

只需将您猜中的单词保留在变量中即可。另外,我建议不要像使用固定范围那样使用,而是获取所选单词的长度

def guess():
    words = ('linux', 'windows')
    correct_word = random.choice(words)
    guessed_word = ["-" for letter in correct_word]
    for n in range(len(correct_word)):
        guess = input('Enter a letter: ')
        for i in range(len(correct_word)):
            if correct_word[i] == guess:
                guessed_word[i] = guess
        print("So far you have: ", "".join(x for x in guessed_word))

答案 3 :(得分:0)

这是给您的快速草稿,我坚信您可以实施您的完整想法:

import random

WORDS = ('linux', 'windows')
correct_word = random.choice(WORDS)

question = list( '-' * len(correct_word))
for n in range(5):
    guess = input('Enter a letter: ')
    for index, letter in enumerate(correct_word):
        if letter is guess:
            question[index] = letter
    print("So far you have: ", ''.join(question))