使用字符串

时间:2018-05-16 16:27:12

标签: python python-2.7 while-loop

我有一个问题,我需要找到一个字符串中的字母数量。我的代码(有点)起作用,因为它可以检测字母是否在单词中。但是,它只能写一个。例如,如果我输入" Word"作为单词和" O"作为字母,它检测到该单词有1" o"。但是,如果我输入" Woord"," O"作为字母,它重复循环并且不输出任何东西。

stop = True

while stop:
    word = raw_input ("Give me a word! ")
    letter = raw_input ("Give me a letter! ")
    count = word.find(letter)
    if count == -1:
        print "The letter,",letter,"is found in the word,",word,"0 times."
        print "Please try again!"
        count = 0
    if count >= 1:
         print "The letter,",letter,"is found in the word,",word,count,"times."
         stop = False

1 个答案:

答案 0 :(得分:1)

你可以这样做:

word = raw_input ("Give me a word! ")
letter = raw_input ("Give me a letter! ")
print(word.count(letter))

它会打印单词的频率

你想知道为什么你的代码不能正常工作或者这已经足够好了吗?