Counting Letters

Simple Solution: Counting a Single Letter

We have previously discussed the solution to the problem of counting the number of times a specific letter appears in a string. In the case below, that specific letter is “a”.

Of course, we could also solve this problem by using the count method provided for strings.

def countA(text):

    return text.count("a")

General Solution: Counting All Letters

Now we will generalize the counting problem and consider how to count the number of times each letter appears in a given string. In order to do this we need to realize that writing a function that returns a single integer will no longer work. Instead we will need to return some kind of collection that holds the counts for each character.

Although there may be many possible ways to do this, we suggest a dictionary where the keys of the dictionary will be the letters in the string and the associated values for each key will be the number of times that the letter appeared.

What about a letter that does not appear in the string? It will never be placed in the dictionary. By assumption, any key that is not in the dictionary has a count of 0.

If we call the function countAll, then a call to countAll would return the dictionary. For example,

print(countAll("banana"))

would return the dictionary

{"a":3, "b":1, "n":2}

Here is a start to the development of the function.

  1. Define the function to require one parameter, the string.

  2. Create an empty dictionary of counts.

  3. Iterate through the characters of the string, one character at a time.

You have attempted of activities on this page
Next Section - Letter Count Histogram