How to extract numbers from a string in Python?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
Extracting numbers from text is a common Python task because logs, filenames, product codes, and user input often mix words with numeric values. The best solution depends on which numeric forms you care about: whole numbers, signed values, decimals, or identifiers with leading zeroes.
For most programs, the easiest tool is the re module. If the rules are very custom, a small manual parser can be easier to reason about than a complicated regular expression.
Use re.findall for the Simple Case
If the string only contains positive integers, a digit pattern is enough:
Output:
re.findall returns the matches in order as strings. Converting them to int is appropriate only if you want to do arithmetic with them.
Match Signed Numbers and Decimals
If the input can contain values such as -4 or 18.5, \d+ is too narrow because it splits the number into separate pieces. Use a pattern that reflects the shapes you expect:
This pattern has three parts:
- '
-?allows an optional minus sign' - '
\d+matches one or more digits' - '
(?:\.\d+)?allows an optional decimal part'
If your data also contains scientific notation, currency, or locale-specific commas, expand the pattern to match those exact forms instead of guessing.
Keep Matches as Strings When Formatting Matters
Sometimes the numeric text is not really a number for arithmetic purposes. Batch codes, zip codes, and padded identifiers can lose meaning if you convert them to integers:
If you converted these values to int, the leading zeroes would disappear. That is correct mathematically, but wrong if the original formatting is significant.
Manual Parsing for Custom Rules
Regular expressions are compact, but they are not always the clearest option. If you want tight control over what counts as a number, scanning the string manually can be easier to maintain:
This approach is useful when the parser must skip specific regions, stop after the first match, or apply business rules that are awkward to encode in one regex.
Common Pitfalls
The most common mistake is choosing a pattern that is too simple for the real input. \d+ is fine for positive integers, but it fails for negatives, decimals, and scientific notation.
Another pitfall is using str.isdigit() on tokens such as price=19 or v2. isdigit() only returns True when the entire string is digits, so mixed tokens need regex or manual scanning.
Developers also convert matches to integers too early. That can silently remove leading zeroes or raise errors if the input includes decimal points. Keep the raw text until you know which numeric type is appropriate.
Finally, test against real input samples. Data from users, OCR, logs, or spreadsheets often contains commas, currency symbols, or unexpected spacing that simple examples do not reveal.
Summary
- Use
re.findall(r"\d+", text)when the input contains only positive whole numbers. - Expand the regex when you need negatives or decimals.
- Keep matches as strings if formatting matters, especially for identifiers with leading zeroes.
- Use manual parsing when the extraction rules are business-specific and a regex becomes hard to read.
Related reading
- How to extract text from a PDF file via python?
- How to extract the decision rules from scikit-learn decision-tree?
- How to filter a dictionary according to an arbitrary condition function?
- How to filter Pandas dataframe using 'in' and 'not in' like in SQL
- How to filter Pandas dataframe using 'in' and 'not in' like in SQL
- How to filter rows containing a string pattern from a Pandas dataframe
- How to filter rows in pandas by regex
- How to find a Python package's dependencies
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.