Extract the First Number from a String

During my decade of working as a Python developer, I have often encountered messy datasets that need urgent cleaning.

One of the most frequent tasks I face is pulling a specific numeric value out of a long, cluttered string of text.

Whether I am processing US census data or scraping retail prices from a New York-based e-commerce site, I always need to find that first digit quickly.

In this tutorial, I will show you exactly how to find the first number in a string using Python through several efficient methods.

Find the First Number in Python

In real-world Python applications, data rarely arrives in a perfect format.

You might have a string like “The shipping cost to Chicago is 25 dollars,” and you only need that ’25’.

As a Python expert, I have learned that the “best” method usually depends on whether you need a single digit or the entire first multi-digit number.

Let’s look at the different ways I handle this in my day-to-day Python programming.

Method 1: Use Python Re.search() (The Professional Way)

When I want a reliable solution, I almost always reach for the Regular Expression (re) module in Python.

The re.search() function is incredibly powerful because it scans the string and stops as soon as it finds the first match.

In this Python example, I will extract the first sequence of numbers from a string containing California real estate data.

import re

# Sample data: A typical US real estate listing string
listing_description = "The luxury apartment at 5th Avenue costs $4500 per month."

# We use the \d+ pattern to find the first sequence of digits
match = re.search(r'\d+', listing_description)

if match:
    first_number = match.group()
    print(f"The first number found in the Python string is: {first_number}")
else:
    print("No number was found in the string.")

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

find first number in string python

I prefer this Python method because \d+ identifies the whole number (like 4500) rather than just the first digit (4).

If you only need the very first digit, you can simply use \d without the plus sign in your Python code.

Method 2: Use Python List Comprehension and Isdigit()

If I am working on a script where I want to avoid importing extra libraries, I use a Python list comprehension.

This approach is very “Pythonic” and stays readable for other developers on my team.

Here is how I use this Python technique to find the first digit in a string representing a Texas speed limit sign.

# Sample data: A US road sign description
road_sign = "The speed limit on I-10 in Texas is 75 mph."

# We iterate through the string and collect all digits into a list
digits = [char for char in road_sign if char.isdigit()]

# Then we simply grab the first element of that list
if digits:
    first_digit = digits[0]
    print(f"The first digit identified by Python is: {first_digit}")

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

python find first number in string

While this Python method is elegant, keep in mind it only returns the first individual digit.

In the example above, it would return ‘7’, not ’75’. I use this when I only care about the starting numeric character.

Method 3: Use a Python For Loop with the Next() Function

In my experience, efficiency is key when processing large Python datasets. Using a Python next() function combined with a generator expression is much faster than creating a full list.

This Python method stops iterating the moment it finds the first number, saving memory and time.

# Sample data: US Treasury bond info
bond_info = "The current interest rate for the 10-year Treasury bond is 4 percent."

# This Python generator finds the first character that satisfies isdigit()
first_digit = next((char for char in bond_info if char.isdigit()), None)

if first_digit:
    print(f"Python found the first digit: {first_digit}")
else:
    print("No digits were found.")

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

python find first digit in string

I find this Python approach very useful when I am dealing with millions of strings in a data pipeline. It is a clean, one-line Python solution that performs exceptionally well.

Method 4: Use Python Filter() and Lambda Functions

Another functional programming approach I often use in Python involves the filter() function. This is a great Python tool for separating the wheat from the chaff in a string.

Let’s look at an example involving a delivery address in Washington D.C.

# Sample data: A US delivery address
delivery_note = "Please leave the package at 1600 Pennsylvania Avenue."

# We filter the string to keep only numeric characters
numeric_filter = filter(str.isdigit, delivery_note)

# Convert the filter object to a list or use next()
first_digit = next(numeric_filter, None)

print(f"The first number in the address according to Python is: {first_digit}")

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

python extract first number from string

I like using filter() because it clearly expresses the intent of the Python code to anyone reading it later.

Method 5: Extract the First Number Using Python String Slicing

Sometimes, I know that the number will always appear after a certain keyword in my Python string.

If the string format is consistent, like a US Invoice, I use Python’s index() and slicing.

# Sample data: A standard US invoice string
invoice_text = "Invoice Number: 90210 - Date: 2023-10-12"

# I find where the digits start manually
for i, char in enumerate(invoice_text):
    if char.isdigit():
        print(f"First number found at index {i} is: {char}")
        break

This Python method is more manual, but it gives me total control over the iteration process.

Method 6: Find the First Float or Decimal in Python

Often, the “number” I’m looking for isn’t an integer but a decimal value, like a US dollar amount ($19.99).

In these cases, the standard isdigit() check fails because of the decimal point. I use a modified Python Regex pattern to handle this specific scenario.

import re

# Sample data: A gas price in Florida
gas_price_str = "The price of unleaded gas in Miami is 3.45 per gallon."

# This Python regex accounts for optional decimal points
match = re.search(r'\d+\.\d+|\d+', gas_price_str)

if match:
    print(f"The first numeric value found by Python is: {match.group()}")

This Python technique is my “gold standard” when I need to extract prices or percentages from American financial reports.

Common Issues to Avoid in Python

When you are trying to find the first number in a Python string, you must be careful with negative numbers.

A simple isdigit() check will ignore the minus sign. If your Python project involves temperature data from Alaska (like -15 degrees), make sure your Regex includes r’-?\d+’.

Another thing I have learned over the years is to always handle the “None” case. If your Python code assumes a number will always be there, your program will crash the moment it hits a string without digits.

Which Python Method Should You Choose?

If you need the entire number (like “100”), use the Python Re.search() method. It is the most robust.

If you just need the very first digit (like “1”), the Python next() and isdigit() approach is the fastest.

I generally stay away from manual loops unless the string structure is extremely complex and requires custom logic.

Python provides so many built-in tools that a manual for-loop is rarely the most efficient path.

I hope this guide helps you handle your Python string manipulation tasks more effectively. Using these Python techniques has saved me countless hours of manual data entry over my career.

The more you practice these Python methods, the more natural they will feel in your development workflow.

If you have a very specific string format that these methods don’t cover, I usually recommend testing your logic on a small subset of data first.

You may also 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.