Search code examples
pythoncounterwordsletters

How to count the letters in a word?


I am trying to make a Python script which counts the amount of letters in a randomly chosen word for my Hangman game.

I already looked around on the web, but most thing I could find was count specific letters in a word. After more looking around I ended up with this, which does not work for some reason. If someone could point out the errors, that'd be greatly appreciated.

wordList = ["Tree", "Fish", "Monkey"]
wordChosen = random.choice(wordList)
wordCounter = wordChosen.lower().count['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
print(wordCounter)

Solution

  • First off, your code contains an error that is rather important to understand:

    wordChosen.lower().count['a', 'b'] #...
    

    count is a function and so it requires you to surround its parameters with parentheses and not square brackets!

    Next you should try to refer to Python Documentation when using a function for the first time. That should help you understand why your approach will not work.

    Now to address your problem. If you want to count the number of letters in your string use len(wordChosen) which counts the total number of characters in the string.

    If you want to count the frequencies of each letter a few methods have already been suggested. Here is one more using a dictionary:

    import string
    LetterFreq={}
    for letter in string.ascii_lowercase:
        LetterFreq[letter] = 0
    for letter in wordChosen.lower():
        LetterFreq[letter] += 1
    

    This has the nice perk of defaulting all letters not present in the word to a frequency of 0 :)

    Hope this helps!