Lesson·difficulty 2/5·~15 min
Regex: pull out the numbers
Read the task → edit your code → Run to see the output → Run tests to check your answer.
A regular expression describes a text pattern. The re module finds and
transforms text that matches it:
python
import re
re.findall(r"\d+", "a12b3") # ['12', '3'] — every run of digits
re.sub(r"\s+", "-", "a b c") # 'a-b-c' — collapse whitespace
Key pieces: \d matches a digit, + means "one or more", and findall
returns every non-overlapping match as a list of strings.
Your task
Write extract_numbers(text) that finds every whole number in text and
returns them as a list of ints, in the order they appear.
python
extract_numbers("order 12 apples and 3 pears") # [12, 3]
extract_numbers("room 404: not found") # [404]
extract_numbers("no digits here") # []
Hint: a findall with a one-or-more-digits pattern (you saw it above) hands you
the numbers as strings — then convert each match to an int.
Tests
- two numbers
- single number
- no numbers
- digits glued to text
✦ Need help with this task?
Sign in or create a free account to get AI help. Free includes a monthly AI allowance.
warming up
Loading editor…
Consolewaiting
$ Console output will appear here.