chapter four
4 Creating functions using regexen
Very often in Python, or in other programming languages, you will want to wrap a regular expression in a small function rather than repeat it inline.
Puzzle 10 Reimplementing str.count()
Summary
Create a function equivalent to str.count() using regular expressions.
The Python method str.count() is widely useful to find substrings inside a larger string. For example, here is some typical code you might write:
# Lyric from song "Hot Knife" by Fiona Apple
>>> s = """If I'm butter, if I'm butter
If I'm butter, then he's a hot knife
He makes my heart a CinemaScope screen
Showing the dancing bird of paradise
"""
>>> s.count('e')
15
>>> s.count('tt')
3
Imagine that Python did not have the method str.count() but you wished to implement a similar function by utilizing regular expressions, with the signature:
def my_count(substring: str, string: str) -> int:
# re.sub(..., ...) # maybe something like this?
...
Author thoughts How can a regex count the substring occurrences?
Two functions in the Python re module seem especially likely to be useful. The re.sub() function will replace a pattern with something else. We might try a solution using that, for example:
>>> def my_count(substring, string):
... return len(re.sub(fr"[^{substring}]", "", string))
>>> my_count('e', s)
15
>>> my_count('tt', s) # Oops, this goes wrong
10