How to Find Numbers in a String Using Python

I was working on a project where I had to extract numerical data from messy text files. These files contained customer IDs, invoice numbers, and ZIP codes, all mixed with text.

If you’ve ever worked with unstructured data in Python, you know how tricky it can be to find numbers hidden inside strings. I’ve faced this challenge many times in my experience as a Python developer, and over the years, I’ve discovered a few simple and reliable ways to handle it.

In this tutorial, I’ll show you four easy methods to find numbers in a string using Python. We’ll go step-by-step, starting with simple built-in functions and then moving to more powerful techniques using regular expressions.

Find Number in String Python

You can use different methods in Python to find the number in a string. Each method has its pros and cons, which you will understand while analysing the code of each method.

Method 1: Use findall() Method in Python

The Python re module has a function called findall(), which finds a pattern in a string and returns the specified pattern, such as a number. Here, the concept of regular expression is used.

Let’s look at the code below as an example.

import re  # Importing the regular expressions module

# Sample text containing prices in dollars
text = "The price of the book is $49.99 and the notebook is $5.50."

# Use re.findall() to find all occurrences in the text that match the given pattern
# The pattern '\d+\.\d+|\d+' matches either:
# - '\d+\.\d+': one or more digits followed by a dot and one or more digits (matching decimal numbers)
# - or '\d+': one or more digits (matching integer numbers)
numbers = re.findall(r'\d+\.\d+|\d+', text)

# Print the list of numbers found in the text
print(numbers)

You can refer to the screenshot below to see the output.

Find Number in String Python Using findall() Method

The output shows that the method findall() returns the dollars from the text like [‘49.99’, ‘5.50’].

Method 2: Use isdigit() and split() Method in Python

The split() method splits the text or string into words, and isdigit() checks whether the word consists of a digit. Also, you will use the list comprehension to create a list of numbers found in the string.

For example, run the code below.

# Sample text containing numbers and words
text = "There are 10 bananas and 20 mango."

# Using a list comprehension to find and convert numeric words to integers
# text.split() splits the text into a list of words
# The for loop iterates over each word in the split text
# word.isdigit() checks if the word consists only of digits
# int(word) converts the numeric string to an integer
numbers = [int(word) for word in text.split() if word.isdigit()]

# Print the list of numbers found in the text
print(numbers)

You can refer to the screenshot below to see the output.

Find Number in String Python Using isdigit() and split() Method

The output shows that the numbers from the sample text are extracted as a list of numbers.

Method 3: Use Python’s isnumeric() Method

The isnumeric() method is used to check whether the current word is numeric. Here, you will use the for loop to iterate over each word of the string, then check if the current word is numeric or not; if numeric, then append it to an empty list.

For example, execute the code below.

# Sample string containing numbers and words
test_string = "I have 3 dogs and 2 cats"

# Print the original string
print("The original string: " + test_string)

# Initialize an empty list to store the numbers
res = []

# Split the string into a list of words
x = test_string.split()

# Iterate over each word in the split list
for i in x:
    # Check if the word is numeric
    if i.isnumeric():
        # Convert the numeric string to an integer and append to the result list
        res.append(int(i))

# Print the list of numbers found in the string
print("The numbers list is: " + str(res))

You can refer to the screenshot below to see the output.

Find Number in String Python Using isnumeric() Method

The output shows that the two numbers from the string are extracted and stored in the list like this [3, 2].

Method 4: Use filter() Method

You can use the filter() method with string methods to extract the numbers from the string.

For example, look at the code below.

# Sample text containing numbers mixed with other characters
text = "Room 123, Level 2, Building 45."

# Use filter() to extract only the digits from the text
# filter(str.isdigit, text) creates an iterator that includes only digit characters from the text
# ''.join(...) joins these digits into a single string
numbers = ''.join(filter(str.isdigit, text))

# Print the resulting string of concatenated digits
print(numbers)

You can refer to the screenshot below to see the output.

Find Number in String Python Using filter() Method

From the output, you can see that the filter() method with isdigit() and join() method extracts the number from the string.

Method 5: Use Python’s isdigit() Method

The isdigit() method also checks whether the current character is a digit. So, using this, you can iterate over each string character and then check whether it is a digit. If it is a digit, then add the character to the string.

For example, run the code below.

# Sample string containing numbers and words
test_string = "I have 3 dogs and 2 cats"

# Initialize an empty list to store the numbers
numbers = []

# Iterate over each character in the string
for char in test_string:
    # Check if the character is a digit
    if char.isdigit():
        # Convert the digit character to an integer and append to the numbers list
        numbers.append(int(char))

# Print the list of numbers found in the string
print("The numbers list is:", numbers)

You can refer to the screenshot below to see the output.

Find Number in String Python Using isdigit() Method

Look at the output to see how the numbers are extracted from the string and stored in the list [3, 2].

Finding numbers in a string using Python is a common task in data analysis, web scraping, and text processing.

You’ve now learned five easy methods, from simple built-ins like isdigit(), findall(), split(), isnumeric(), and filter() methods. Personally, I rely on regex most of the time because it’s flexible and works across a wide range of data formats.

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.