Search⌘ K

Finding all occurrences of a pattern

Explore how to use Python's re module and its findall() function to identify all occurrences of a pattern within a string. Understand how regular expressions work in Python, see examples with sequences of letters and numbers, and grasp why overlapping matches are not returned. This lesson helps you apply findall() effectively in string processing tasks like alphametic puzzles and pattern searching.

We'll cover the following...

The first thing this alphametics solver does is find all the letters (A–Z) in the puzzle.

Python 3.5
import re
print (re.findall('[0-9]+', '16 2-by-4s in rows of 8')) #①
#['16', '2', '4', '8']
print (re.findall('[A-Z]+', 'SEND + MORE == MONEY')) #②
#['SEND', 'MORE', 'MONEY']

① The re module is Python’s implementation of regular expressions. It has a nifty function called findall() which takes a regular expression pattern and a string, and finds all occurrences of ...