首页 > 解决方案 > Python:有没有办法只打印字符串中的指定字符,而让其他字符为空?

问题描述

我是 Python 编程的新手,我想做一个小刽子手代码。我几乎完成了它,但目前有一些事情是不完整的。我试图为我的问题找到一个合适的答案,但我什么也没找到,所以我希望你能帮助我。

假设有以下几行代码:

word = "testing"
guess = input("Tell me a letter ")

if guess in word:
    print("You are correct. This letter is at the index " + str(word.index(guess)))

我有两个问题:

  1. 为了打印猜测的字符并让其他字符空白,我需要做什么?例如,假设我猜到了字母i,所以这封信在索引号 4 处,所以我想打印它,所以它看起来像这样: xxxxixx

  2. 字符串测试包含 2 个t字符。如果我猜到了t字符,那么我只能看到第一个t而不是第二个:

     Tell me a letter t
     You are correct. This letter is at the index 0
    

我该怎么做才能同时显示第二个字符?

标签: pythonprinting

解决方案


我认为,更好的解决方案之一是定义一个函数,给定word和猜测的字母(知道哪个是当前猜测的字母),将返回tXXtXXX结果以及猜测的字母的位置。

这是它的样子:

def get_positions_and_partial_word(word, current_guess, all_correct_guesses=[]):
    """Given a word (like "testing"), the current guess (like "t"),
       and a list of correct_guesses so far, this function will return
       a list of the positions of the guess (which will be empty if not
       a correct guess), and the partial word (like "tXXtXXX")."""

    current_guess_positions = []
    partial_word = ""

    # Populate the current_guess_positions and the partial_word:
    for i,c in enumerate(word):
        if c == current_guess or c in all_correct_guesses:
            partial_word += c
        else:
            partial_word += "X"

        if c == current_guess:
            current_guess_positions.append(i)

    return current_guess_positions, partial_word

你看到发生了什么事吗?我想返回当前猜测的位置(可能不止一个,所以我返回一个列表),我想返回部分单词。因此,我遍历 中的字符 ( c) word,跟踪索引 (as i),并创建(逐个字母)partial_word,并将位置添加到current_guess_positions. 循环完成后,我返回它们。

你可以这样称呼它:

positions, partial_word = get_positions_and_partial_word('testing', 't', [])

然后positions将设置为[0, 3],并将partial_word设置为tXXtXXX

如果它是正确的,您仍然需要将字母添加到正确猜测列表中(需要将其作为get_positions_and_partial_word()函数的最后一个参数传入),但我会让您自己弄清楚。:-)


推荐阅读