【问题标题】:How to replace the specified dash with the letter如何用字母替换指定的破折号
【发布时间】: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


【解决方案1】:

如果您以后不打算使用正确猜测的位置,那么您可以简化最后一段代码:

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-'

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

【讨论】:

    【解决方案2】:

    需要注意的几点:

    • 低效/un-pythonic pop 操作(参见this
    • l_count 只是 len(word)
    • un-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
                
    

    【讨论】:

    • 谢谢。您可能应该意识到并注意字符串对象没有称为“附加”的属性
    【解决方案3】:

    它替换了所有的哈希

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-28
      • 1970-01-01
      • 2011-03-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多