Python 查找字符串中出现的所有字符
我对python真的是个新手,正在尝试构建一个用于练习的刽子手游戏。Python 查找字符串中出现的所有字符,python,string,python-3.6,Python,String,Python 3.6,我对python真的是个新手,正在尝试构建一个用于练习的刽子手游戏。 我正在使用Python 3.6.1 用户可以输入一个字母,我想告诉他单词中是否出现了该字母以及该字母的位置。 我使用executions=currentWord.count(guess) 我有firstLetterIndex=(currentWord.find(guess))来获取索引。 现在我有了第一个字母的索引,但是如果这个单词有这个字母多次呢? 我尝试了secondLetterIndex=(currentWord.f
我正在使用Python 3.6.1
用户可以输入一个字母,我想告诉他单词中是否出现了该字母以及该字母的位置。
我使用
executions=currentWord.count(guess)
我有
firstLetterIndex=(currentWord.find(guess))
来获取索引。现在我有了第一个字母的索引,但是如果这个单词有这个字母多次呢?
我尝试了
secondLetterIndex=(currentWord.find(猜测[firstLetterIndex,currentWordlength])
,但没有成功。有更好的方法吗?可能是我找不到的内置函数?一种方法是使用列表理解查找索引:
currentWord = "hello"
guess = "l"
occurrences = currentWord.count(guess)
indices = [i for i, a in enumerate(currentWord) if a == guess]
print indices
输出:
[2, 3]
我将保留第二个布尔值列表,指示哪些字母已正确匹配
>>> word_to_guess = "thicket"
>>> matched = [False for c in word_to_guess]
>>> for guess in "te":
... matched = [m or (guess == c) for m, c in zip(matched, word_to_guess)]
... print(list(zip(matched, word_to_guess)))
...
[(True, 't'), (False, 'h'), (False, 'i'), (False, 'c'), (False, 'k'), (False, 'e'), (True, 't')]
[(True, 't'), (False, 'h'), (False, 'i'), (False, 'c'), (False, 'k'), (True, 'e'), (True, 't')]
提示:
find
有一个可选参数start
,可能对您有用。可能是@Kevin的副本我知道,我(尝试)使用了它secondLetterIndex
。我试着从第一个字母的索引开始,以单词的长度结束。不起作用。如果您说“我在执行secondLetterIndex=(currentWord.find(guess[firstLetterIndex,currentWordlength]))
时尝试了双参数形式,那么您实际上并没有在那里使用双参数形式。您正在将一个参数guess[firstLetterIndex,currentWordlength]
传递给find
enumerate()
可能是一个更好的选择[i for i,c in enumerate(currentWord)如果c==guess]
我可以自己调用2吗?像indieces[0]
或类似的东西?是的,如果您只需要索引的第一个元素,您可以这样做。您可以创建matched asmatched=[False]*len(word\u to\u guess)
并避免循环,这是一种不好的做法;它只适用于不可变值。这导致了无数的问题,比如“设置x=[[]]*5
的代码有什么问题?”。