【发布时间】:2021-08-09 02:02:41
【问题描述】:
我想写一个刽子手程序,为此,我必须用用户猜测的字母 (guess) 替换散列 ('-') 字母。但是当我运行代码时,它会用用户的猜测字母替换所有哈希值。
代码看起来不错,但我没有得到想要的结果。
-
words是我在函数之前写的单词列表。
def word_guess():
random.shuffle(words)
word = words[0]
words.pop(0)
print(word)
l_count = 0
for letter in word:
l_count += 1
# the hidden words are shown a '-'
blank = '-' * l_count
print(blank)
guess = input("please guess a letter ")
if guess in word:
# a list of the position of all the specified letters in the word
a = [i for i, letter in enumerate(word) if letter == guess]
for num in a:
blank_reformed = blank.replace(blank[num], guess)
print(blank_reformed)
word_guess()
例如:当word 为'funny',guess 为'n'时,输出为'nnnnn'。
我应该如何将所需的哈希字符串替换为guess 字母?
【问题讨论】:
-
我会朝相反的方向走。跟踪正确猜到的字母,并显示
''.join([x if x in correct_guesses else '-' for x in word])。
标签: python character-replacement