Extract the Prices
Write extract_prices(text) that finds every price in a piece of text and returns them as a list of floats, in the order they appear.
A price is a dollar sign $ immediately followed by digits, optionally with thousands commas (1,234) and optionally exactly two decimal digits (.50). Numbers without a $ are not prices.
Understand the problem
Build the pattern in pieces.
In a regular expression, what does \$ match?
- The end of the line
- A literal dollar sign
- Any character
In a pattern $ normally means "end of the line", so a literal dollar sign must be escaped with a backslash: \$. Use a raw string (r"...") so Python does not treat the backslash itself as an escape.
Which pattern matches a whole number such as 1,234 or 12?
\d+\d{1,3}(?:,\d{3})+|\d+[0-9]*
First try digits with comma groups (1,234 or 1,234,567): one to three digits, then one or more groups of a comma and three digits. If that does not match, fall back to plain digits. The (?:...) is a group that does not capture.
What does re.finditer(pattern, text) give?
- A list of strings
- An iterator of match objects, with
.group(1)for each captured part - The first match only
finditer yields a match object for every non-overlapping match. A match has .group(0) (the whole match) and .group(1), .group(2) for the parenthesised parts.
Write the solution
Return the list of floats.
def extract_prices(text):
# Write your code here.
pass
Hint 1: a question to ask yourself
Which three parts does a price have, and which of them are optional?
Hint 2: the shape of the answer
Pattern: \$ then a group for the whole-number part (with commas), then an optional group for \.\d{2}. For each match remove the commas from group 1, add group 2 if present, and convert with float.
Reflect
Solution
import re
PRICE = re.compile(r"\$(\d{1,3}(?:,\d{3})+|\d+)(\.\d{2})?")
def extract_prices(text):
prices = []
for match in PRICE.finditer(text):
whole = match.group(1).replace(",", "")
cents = match.group(2) or ""
prices.append(float(whole + cents))
return prices
What this tests: regular expressions (re.compile, finditer, groups, alternation, optional parts, escaping), and converting matched text.
Build patterns in small steps and test each on awkward text. A regex that works on three examples can fail on the fourth.
Order of alternatives matters: \d{1,3}(?:,\d{3})+|\d+ tries the comma form first. If you wrote \d+ first, $1,234 would match only $1.
Compile once: re.compile at module level avoids rebuilding the pattern on every call.
When not to use a regex: for nested or structured formats (HTML, JSON, CSV, dates) use the proper parser. Regexes are for flat patterns in text.
What an interviewer might ask next: Make the dollar sign optional and also accept the currency code ("USD 5.00"). Why does it make the pattern ambiguous? (Plain numbers such as years would match.)
VISIBLE = 3
CASES = [
(('Coffee $3.50, cake $4, total $7.50',), [3.5, 4.0, 7.5], 'a few prices'),
(('no prices here',), [], 'no prices'),
(('$1,234.99 and $12',), [1234.99, 12.0], 'thousands commas'),
(('it costs 5 dollars or 3.50',), [], 'numbers without a dollar sign'),
(('US$5',), [5.0], 'a prefix before the dollar sign'),
(('$1,000,000',), [1000000.0], 'a million'),
(('',), [], 'empty text'),
(('Only $0.99!',), [0.99], 'punctuation after the price'),
(('$7 $8 $9',), [7.0, 8.0, 9.0], 'prices side by side'),
]