0
0
PythonHow-ToBeginner · 3 min read

How to Extract Numbers from String in Python Easily

To extract numbers from a string in Python, use the re.findall() function with a pattern like \d+ to find all digit sequences. This returns a list of number strings which you can convert to integers if needed.
📐

Syntax

Use the re.findall() function from the re module with a pattern to match digits.

  • re.findall(pattern, string): Finds all matches of pattern in string.
  • \d+: Matches one or more digits in a row.
python
import re
numbers = re.findall(r'\d+', 'Example 123 and 456')
print(numbers)
Output
['123', '456']
💻

Example

This example shows how to extract all numbers from a string and convert them to integers for further use.

python
import re
text = 'I have 2 apples and 15 oranges.'
numbers_str = re.findall(r'\d+', text)
numbers = [int(num) for num in numbers_str]
print(numbers)
Output
[2, 15]
⚠️

Common Pitfalls

One common mistake is forgetting to import the re module before using re.findall(). Another is not converting the extracted strings to numbers if you want to do math with them. Also, using \d instead of \d+ will only match single digits, missing multi-digit numbers.

python
import re
text = 'Room 101'
# Wrong: matches only single digits
single_digits = re.findall(r'\d', text)
print(single_digits)  # ['1', '0', '1']

# Right: matches full numbers
full_numbers = re.findall(r'\d+', text)
print(full_numbers)  # ['101']
Output
['1', '0', '1'] ['101']
📊

Quick Reference

  • re.findall(r'\d+', text): Extracts all numbers as strings.
  • Use list comprehension with int() to convert to integers.
  • Remember to import re before using regex functions.

Key Takeaways

Use re.findall(r'\d+', string) to extract all numbers from a string.
Convert extracted number strings to integers with int() for calculations.
Always import the re module before using regex functions.
Use \d+ to match full numbers, not just single digits.
Check your regex pattern carefully to avoid missing numbers.