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 ...

Get Regular Expression Puzzles and AI Coding Assistants now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.