Counting letters in a string
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.
= "How far that little candle throws its beams! " \
s "So shines a good deed in a naughty world."
= {}
d for char in s.lower():
try:
+= 1
d[char] except KeyError:
= 1 d[char]
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.
Copyright © 2023–2025 Clayton Cafiero
No generative AI was used in producing this material. This was written the old-fashioned way.
Footnotes
William Shakespeare, The Merchant of Venice, Act V, Scene I (Portia).↩︎