如何用字母替换指定的破折号

How to replace the specified dash with the letter

我想编写一个刽子手程序,为此,我必须用用户猜测的字母 (guess) 替换井号 ('-')。但是当我 运行 代码时,它会用用户的猜测字母替换所有的哈希值。 代码看起来没问题,但我没有得到想要的结果。

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 字母替换所需的哈希字符串?

it replaces all the hashes

This is exactly what blank.replace is supposed to do,不过

您应该做的是替换字符串的那个单个字符。由于字符串是不可变的,因此您不能真正做到这一点。然而,lists 的字符串是可变的,所以你可以做 blank = ['-'] * l_count,这将是一个破折号列表,然后修改 blank[num]:

for num in a:
   blank[num] = guess
   print(blank)

有几点需要注意:

  • inefficient/un-pythonicpop操作(见this
  • l_count 就是 len(word)
  • 非 pythonic,不可读的替换

相反,这里有一个更好的实现:

def word_guess() -> str:
    random.shuffle(words)
    word = words.pop()
    
    guess = input()

    out = ''
    for char in word:
        if char == guess:
            out.append(char)
        else:
            out.append('-')
    return out
            

如果以后不打算使用猜对的位置,那么可以将最后一段代码精简一下:

word = 'hangman'
blank = '-------'
guess = 'a'

if guess in word:
    blank_reformed = ''.join(guess if word[i] == guess else blank[i] for i in range(len(word)))
    
blank_reformed
'-a---a-'

(您还有一些工作要做才能使整个游戏正常运行...)