python - 如何根据位置替换字符串中多个相同的字符?

标签 python string

所以我正在为刽子手制作一个程序,到目前为止就是这样,

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/

相关文章:

java - 使用 Eclipse 导入 py4j

c++ - 在 C++ 中使用带有 <string> 的 vector Push_back 时出现错误

python - 如何让 Sphinx 测试文档中嵌入的代码?

python - 如何强制 `setup.py test` 将依赖项安装到我的 `virtualenv` 中?

python - 如何更改绘图图形大小

java - 将整数数组列表转换为基于ascii表的字符串并与字符串进行比较

php - str_replace 工作不正确 ("str_replace"对 $replace 参数进行了更改)

c++ - C++中如何处理长字符串?

java - java - 如何在不考虑空格的情况下比较java中的两个字符串?

python - 如何在elasticsearch python低级客户端中指定index.mapping.ignore_malformed?