If I have a list of words (as in this exercise), can I count letters or parts of words, not whole words. For example, how many letters “a” there are in the list of names?
Plain answer, yes, we can do anything we like with the words we are iterating over.
For example, ‘how many "a"s are there in a list of provided words?’
words = ['able', 'table', 'cable', 'label', 'stable', 'fable']
Given the above list we can iterate over it and examine each word, then naively iterate over the word and count the target letter.
a_count = 0 for word in words: for char in word: if char == 'a': a_count = a_count + 1 print (a_count) # 6
Thanks, it works!
For those, who is here with the same question as mine:
Basing on the answer a little search in internet helped to figure out how to search for a certain part (string) in each word in the list. Modified example of Mtf:
words = [‘able’, ‘table’, ‘cable’, ‘label’, ‘stable’, ‘fable’]
a_count = 0
for word in words:
if ‘ab’ in word:
a_count = a_count + 1
print (a_count) #6