Find the First Number in a String in Python

One of my machine learning team members struggled to find the first number in a string in Python. I suggested a few useful methods. In this tutorial, I will show you how to find the first number in a string in Python.

To find the first number in a string using Python, you can utilize the re module with a regular expression. First, import the re module and define a pattern to match one or more digits using r'\d+'. Then, use re.search(pattern, your_string) to search for the pattern in the string. If a match is found, retrieve the first number with match.group(). For example:

import re

text = "The price is 100 dollars"
pattern = r'\d+'
match = re.search(pattern, text)
if match:
    first_number = match.group()
    print(f"The first number in the string is: {first_number}")

This will output: The first number in the string is: 100.

Python Find First Number in String

This is a very common requirement for Python developers. For example, suppose you want to extract numerical data from mixed-content strings. Or may be you want to ensure that a string contains a number before processing it. These kinds of requirements are very common while working with machine learning.

Let me now show you four different methods of finding the first number in a string in Python.

Method 1: Using Regular Expressions (re module)

The re module in Python provides a powerful way to search for patterns in strings. Here’s how you can use it to find the first number in a string.

Syntax

Here is the syntax for using the re module for pattern matching.

import re

pattern = r'\d+'
match = re.search(pattern, your_string)
if match:
    first_number = match.group()

Here

  • import re: Imports the regular expressions module.
  • pattern = r'\d+': Defines a pattern to match one or more digits.
  • re.search(pattern, your_string): Searches for the pattern in the string.
  • match.group(): Returns the matched number as a string.

Now, let me show you an example.

Example

import re

text = "The price is 100 dollars"
pattern = r'\d+'
match = re.search(pattern, text)
if match:
    first_number = match.group()
    print(f"The first number in the string is: {first_number}")

This will output:

The first number in the string is: 100

You can see the exact output in the screenshot below:

python find first number in string

Check out Find the Largest and Smallest Numbers in Python

Method 2: Using a Loop

We can also use Python loops to find the first number in a string. Let me show you the syntax and example.

Syntax

Here is the syntax.

def find_first_number(s):
    for char in s:
        if char.isdigit():
            return char
    return None

Here:

  • char.isdigit(): Checks if the character is a digit.
  • return char: Returns the first digit found.

Example

Let me show you an example to help you understand more.

def find_first_number(s):
    for char in s:
        if char.isdigit():
            return char
    return None

text = "The price is 100 dollars"
first_number = find_first_number(text)
if first_number:
    print(f"The first number in the string is: {first_number}")
else:
    print("No number found in the string.")

This will output:

The first number in the string is: 1

I executed the above Python code, and you can see the exact output in the screenshot below:

find first number in string python

Check out Sum of Digits of a Number in Python

Method 3: Using List Comprehension and next()

List comprehension combined with the next() function can also be used to find the first number in a string.

Syntax

first_number = next((char for char in your_string if char.isdigit()), None)

Here:

  • char.isdigit(): Checks if the character is a digit.
  • next(): Returns the first digit found or None if no digit is found.

Example

Here is an example and the complete Python code.

text = "The price is 100 dollars"
first_number = next((char for char in text if char.isdigit()), None)
if first_number:
    print(f"The first number in the string is: {first_number}")

This will output:

The first number in the string is: 1

Here is the exact output in the screenshot below:

python find first digit in string

Read Write a Python Program to Divide Two Numbers

Method 4: Using str.find() and str.isdigit()

Another approach for finding the first number in a string is to use the str.find() method to locate the first digit.

Syntax

def find_first_number_index(s):
    for index, char in enumerate(s):
        if char.isdigit():
            return index
    return -1

Here:

  • enumerate(s): Iterates over the string with index.
  • char.isdigit(): Checks if the character is a digit.
  • return index: Returns the index of the first digit found.

Example

Here is an example.

def find_first_number_index(s):
    for index, char in enumerate(s):
        if char.isdigit():
            return index
    return -1

text = "The price is 100 dollars"
index = find_first_number_index(text)
if index != -1:
    first_number = text[index]
    print(f"The first number in the string is: {first_number}")

This will output:

The first number in the string is: 1

Here, I executed the Python code using VS code, and you can see the output in the screenshot below:

python get first number in string

Conclusion

In Python, you can find the first number in a string in several ways like:

  • Using Regular Expressions (re module)
  • Using a Loop
  • Using List Comprehension and next()
  • Using str.find() and str.isdigit()

I have also included real examples for each method. Do you still have questions? Feel free to leave a comment below.

You may also like:

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.