python - 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)))
我有两个问题:
为了打印猜测的字符并让其他字符空白,我需要做什么?例如,假设我猜到了字母
i
,所以这封信在索引号 4 处,所以我想打印它,所以它看起来像这样:xxxxixx
字符串测试包含 2 个
t
字符。如果我猜到了t
字符,那么我只能看到第一个t
而不是第二个:Tell me a letter t You are correct. This letter is at the index 0
我该怎么做才能同时显示第二个字符?
解决方案
我认为,更好的解决方案之一是定义一个函数,给定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()
函数的最后一个参数传入),但我会让您自己弄清楚。:-)
推荐阅读
- c# - C# 程序在朋友的 PC 上立即关闭
- c# - 如何检查节点的存在和具有特定属性的节点是否存在?
- activemq-artemis - 在 docker 上集群 Artemis 的问题
- ios - 本地主机上的开发 node.js 服务器在 swiftUI 应用程序中返回 nil,但在浏览器中不返回
- python - 如何将具有不同数字的小时/分钟列转换为 python/pandas 中的日期时间对象?
- vim - 是否可以在 vim 缩写 id 中包含回车?
- r - 如何为对数正态分布列绑定蒙特卡罗模拟结果?
- sql - 使用 SQL 请求复制行和编辑值,但需要改进一下
- php - 在前端监控 PHP 执行的正确方法是什么?
- html - 如何从 Nokogiri 返回选择的短语