python - 如何查找单词中某个字母的多个索引? (Python)

标签 python

所以我正在制作一个吊人游戏,并且遇到了有关索引的问题。基本上,我想找到 secret 单词中字母的索引,问题是如果 secret 单词包含两个相同的字母,例如“guacamole”,其中字母 a 的索引为 2 和 4但是当我想找到a的索引时,它只打印“2”而不是“4”。有没有解决的办法?提前致谢!

出现问题的部分代码:

for letter in secret_word:
    if user_guess == letter:
        current_word_index = secret_word.find(letter)
        print(current_word_index) #Not in full program, only to test errors.

完整代码:

#Hanging man

import string

space = "\v"

dbl_space = "\n"


secret_word = str(input("Enter a secret word: "))

guess_low = list(string.ascii_lowercase)

used_letters = []


user_errors = 0

user_errors_max = 1

secret_word_index = int(len(secret_word))

secret_word_placeholder = list(range(secret_word_index))




while user_errors != user_errors_max:
    user_guess = str(input("Enter a letter: "))
    if len(user_guess) != 1:
        print("You have to pick one letter")
    if user_guess in guess_low:
        guess_low.remove(user_guess)
        used_letters.extend(user_guess)
        print(used_letters)
    for letter in secret_word:
        if user_guess == letter:
            current_word_index = secret_word.find(letter)

if user_errors == user_errors_max:
    print("You lost the game, the secret word was: " + secret_word)

最佳答案

这是您想要实现的目标的示例。使用列表理解。

string='hello'
letter='l'
[idx for idx,ch in enumerate(string) if ch==letter]

关于python - 如何查找单词中某个字母的多个索引? (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60279390/

相关文章:

python - 如何通过 http 请求在 Instagram 中获取关注者和关注列表

python - 通过二值图像 Numpy 矩阵的矩阵运算计算均方误差

Python 相似代码不同输出

python - 内容类型 text/plain 的文件扩展名为 .ksh?

python - 如何在python中抛出错误并使用自定义消息退出

python - 微软 LUIS : unable to set time zone (datetimeReference) for datetimeV2 entities

python - 从维基百科抓取网页到 Pandas

Python urllib2.urlopen 返回 302 错误,即使页面存在

python - 如果未指定,默认的 Celery 日志级别是多少?

python - 如何在 mac osx 上安装 python 的 pip 包?