1

I have a problem where I need to find the amount of letters are in a string. My code (somewhat) works as it can detect if a letter is in the word. However, it can only write one. For example, if I input "Word" as the word and "O" as the letter, it detects that word has 1 "o". However, if I input "Woord", and "O" as the letter, it repeats the loop and doesn't output anything.

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
4
  • Use word.count(letter), find only returns the index of the letter not the amount. Commented May 16, 2018 at 16:29
  • My teacher says the word.index() indexes the word. Also, how would I fix this then? Commented May 16, 2018 at 16:31
  • Index would raise an error if you enter a substring which isnt part of the string while find would return -1. As I said use word.count(letter) instead. Commented May 16, 2018 at 16:32
  • Yes! It works. Thanks. Commented May 16, 2018 at 16:34

1 Answer 1

1

you can just do:

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

and it will print the frequency of the word

do you want to know why your code is not working or this is good enough?

Sign up to request clarification or add additional context in comments.

3 Comments

You changed word.find into word.count. Is this the only reason why my code wasn't working? Because of the wrong function?
No, its instead your whole code, these three lines replace your entire code
Okay. I see. However, the code is actually a block of code that I need to hand it. It needs to loop. And needs to give back a proper sentence. However, please tell me if I have any redundant code that isn't needed under my current parameters. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.