Clinton Vlasak Clinton Vlasak - 1 year ago 131
Python Question

Find how many words start with certain letter in a list

I am trying to output the total of how many words start with a letter

in a list from a separate text file. I'm looking for an output such as this.

35 words start with a letter 'a'.

However, i'm outputting all the words that start with an
instead of the total with my current code. Should I be using something other than a for loop?

So far, this is what I have attempted:

wordsFile = open("words.txt", 'r')
words =
wordList = words.split()

print("Words:",len(wordList)) # prints number of words in the file.

a_words = 0

for a_words in wordList:
if a_words[0]=='a':
print(a_words, "start with the letter 'a'.")

The output I'm getting thus far:

Words: 334
abate start with the letter 'a'.
aberrant start with the letter 'a'.
abeyance start with the letter 'a'.

and so on.

Answer Source

You are using the a_words as the value of the word in each iteration and missing a counter. If we change the for loop to have words as the value and reserved a_words for the counter, we can increment the counter each time the criteria is passed. You could change a_words to wordCount or something generic to make it more portable and friendly for other letters.

a_words = 0

for words in wordList:
    if words[0]=='a':
        a_words += 1

print(a_words, "start with the letter 'a'.")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download