问题描述
我对 Python 真的很陌生,正在尝试构建一个 Hangman 游戏以供练习.
我正在使用 Python 3.6.1
用户可以输入一个字母,我想告诉他单词中是否出现了该字母以及它在哪里.
我通过使用 occurrences = currentWord.count(guess)
得到总出现次数
我有 firstLetterIndex = (currentWord.find(guess))
来获取索引.
现在我有了第一个字母的索引,但是如果这个词多次出现这个字母怎么办?
我试过 secondLetterIndex = (currentWord.find(guess[firstLetterIndex, currentWordlength]))
,但这不起作用.
有一个更好的方法吗?也许我找不到内置功能?
I'm really new to python and trying to build a Hangman Game for practice.
I'm using Python 3.6.1
The User can enter a letter and I want to tell him if there is any occurrence of that letter in the word and where it is.
I get the total number of occurrences by using occurrences = currentWord.count(guess)
I have firstLetterIndex = (currentWord.find(guess))
, to get the index.
Now I have the index of the first Letter, but what if the word has this letter multiple times?
I tried secondLetterIndex = (currentWord.find(guess[firstLetterIndex, currentWordlength]))
, but that doesn't work.
Is there a better way to do this? Maybe a build in function i can't find?
推荐答案
一种方法是使用列表推导式查找索引:
One way to do this is to find the indices using list comprehension:
currentWord = "hello"
guess = "l"
occurrences = currentWord.count(guess)
indices = [i for i, a in enumerate(currentWord) if a == guess]
print indices
输出:
[2, 3]
这篇关于查找字符串中所有出现的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!