Counting letters in a string

Published

2023-07-31

Counting letters in a string

Here’s an example of how we can use a dictionary to keep track of the number of occurrences of letters or other characters in a string. It’s common enough in many word guessing and related games that we’d want this information.

Let’s say we have this string: “How far that little candle throws its beams! So shines a good deed in a naughty world.”1

How would we count all the symbols in this? Certainly, separate variables would be cumbersome. Let’s use a dictionary instead. The keys in the dictionary are the individual letters and symbols in the string, and the values will be their counts. To simplify things a little, we’ll convert the string to lower case before counting.

s = "How far that little candle throws its beams! " \
    "So shines a good deed in a naughty world."

d = {}
for char in s.lower():
    try:
        d[char] += 1
    except KeyError:
        d[char] = 1

We start with an empty dictionary. Then for every character in the string, we try to increment the value associated with the dictionary key. If we get a KeyError, this means we haven’t seen that character yet, and so we add a new key to the dictionary with a value of one. After this code has run, the dictionary, d, is as follows:

{'h': 5, 'o': 6, 'w': 3, ' ': 16, 'f': 1, 'a': 7, 'r': 3, 
 't': 7, 'l': 4, 'i': 4, 'e': 6, 'c': 1, 'n': 4, 'd': 5, 
 's': 6, 'b': 1, 'm': 1, '!': 1, 'g': 2, 'u': 1, 'y': 1, 
 '.': 1}

So we have five ‘h’, six ‘o’, three ‘w’, and so on.

We could write a function that reports how many of a given character appears in the string like this:

def get_count(char, d):
    try:
        return d[char]
    except KeyError:
        return 0

This function returns the count if char is in d or zero otherwise.

Original author: Clayton Cafiero < [given name] DOT [surname] AT uvm DOT edu >

No generative AI was used in producing this material. This was written the old-fashioned way.

This material is for free use under either the GNU Free Documentation License or the Creative Commons Attribution-ShareAlike 3.0 United States License (take your pick).

Footnotes

  1. William Shakespeare, The Merchant of Venice, Act V, Scene I (Portia).↩︎