Python
string manipulation
regex
programming tutorial
extract numbers

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.

Browse interview questions

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:

python
1import re
2
3text = "Order 17 ships in 3 days and contains 250 items"
4
5matches = re.findall(r"\d+", text)
6numbers = [int(value) for value in matches]
7
8print(matches)
9print(numbers)

Output:

text
['17', '3', '250']
[17, 3, 250]

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:

python
1import re
2
3text = "Temperatures: -4, 18.5, and 0.75"
4pattern = r"-?\d+(?:\.\d+)?"
5
6values = [float(token) for token in re.findall(pattern, text)]
7print(values)
text
[-4.0, 18.5, 0.75]

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:

python
1import re
2
3text = "Batch IDs: 0042, 0105"
4ids = re.findall(r"\d+", text)
5
6print(ids)
text
['0042', '0105']

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:

python
1def extract_integers(text: str) -> list[int]:
2    result = []
3    current = ""
4
5    for char in text:
6        if char.isdigit():
7            current += char
8        else:
9            if current:
10                result.append(int(current))
11                current = ""
12
13    if current:
14        result.append(int(current))
15
16    return result
17
18
19sample = "Room12 has 4 chairs and 88 books"
20print(extract_integers(sample))
text
[12, 4, 88]

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
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track 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.

Browse interview questions

All Rights Reserved.