所以我正在为刽子手制作一个程序,到目前为止就是这样,
word = input("Enter a word: ").upper()
blanks = (len(word)*"_")
print(blanks)
chances = 5
while blanks.count("_") > 0:
letter = input("Enter a letter: ").upper()
if len(letter) > 1:
print("Please enter one letter only")
if letter in list(word):
blanks = blanks[:word.index(letter)] + letter + blanks[word.index(letter)+1:]
print(blanks)
continue
else:
chances -= 1
if chances > 0:
print("That letter isn't in the word, you have", chances, "chance(s) left")
if chances == 0:
print("You lost. The word was", word.lower())
exit()
print("You win! The word was", word.lower())
我只是在尝试代码,所以我会给出这个词来猜测自己,但是如果我曾经给出过一个重复字母的单词,比如“doggo”。
如果我把字母写成“o”,即使我再次猜到“o”,它也会给出“_ O _ _ _”而不是“_ O _ _ O”。
我可以解决这个问题吗?
最佳答案
这对我有用:
word = input("Enter a word: ").upper()
blanks = (len(word) * "_")
print(blanks)
chances = 5
while blanks.count("_") > 0:
letter = input("Enter a letter: ").upper()
if len(letter) > 1:
print("Please enter one letter only")
if letter in list(word):
for count, character in enumerate(word):
if letter == character:
blanks = blanks[:count] + letter + blanks[count + 1:]
print(blanks)
else:
chances -= 1
if chances > 0:
print("That letter isn't in the word, you have",
chances, "chance(s) left")
if chances == 0:
print("You lost. The word was", word.lower())
exit()
print("You win! The word was", word.lower())
不同之处在于,我们不是进行一次替换,而是迭代该单词以查找所有巧合并对同一字母进行所有必要的替换。
关于python - 如何根据位置替换字符串中多个相同的字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63027297/