Regular expressionsregex-extract-numbers
LessonΒ·difficulty 2/5Β·~15 min
Regex: pull out the numbers
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: re.findall(r"\d+", text) gives you the matches as strings β map them
through int.
Tests
- two numbers
- single number
- no numbers
- digits glued to text
- leading zeros (hidden)
- empty string (hidden)
Stuck? Ask for a spark
warming up
Loading editorβ¦
$ Console output will appear here.