chapter four

4 Creating functions using regex

 

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.

4.1 Reimplementing str.count()

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:

##nbsp;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?
    ...

4.2 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

4.2.1 AI thoughts: Extraordinary machine

4.3 Reimplementing str.count() (stricter)

4.3.1 Author thoughts: Write a Python function with the restrictions given

4.3.2 AI thoughts: The Horars Of War

4.4 Finding a name for a function

4.4.1 Author thoughts: Code is read far more often than it is written

4.4.2 AI thoughts: There are two hard problems in computer science

4.5 Playing Poker (Part 1)

4.5.1 Author thoughts: Functions are a big help in larger programs

4.5.2 AI thoughts: He can’t read my poker face

4.6 Playing poker (part 2)

4.6.1 Author thoughts: Large buildings are built from small bricks

4.6.2 AI thoughts: The Society for Preventing Cruelty to Humans

4.7 Playing poker (part 3)

4.7.1 Author thoughts: You better cheat, cheat, if you can’t win