← Practice
πŸ“– Regular expressionsLearning path
Browsing as guestΒ·Sign in or create a free account to save progress and use tutor tools.
LessonΒ·difficulty 2/5Β·~15 min

Regex: pull out the numbers

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

✦ Stuck? Ask for a spark

Sign in or create a free account to use your monthly AI explainer allowance.

warming up
Loading editor…
Consolewaiting

$ Console output will appear here.

>_AI coach
Sign in or create a free account to chat with the tutor.