Get only the first Number in a String in Python

avatar

Borislav Hadzhiev

Last updated: Sep 23, 2022

banner

Photo from Unsplash

Get only the first Number in a String in Python #

Use the re.search() method to get only the first number in a string, e.g. re.search(r'\d+', my_str).group(). The re.search() method looks for the first location in the string where the provided regular expression produces a match.

main.py
import re my_str = 'bobby12hadz34.com' match = re.search(r'\d+', my_str) if match: # 👇️ First number found: 12 print('First number found:', match.group()) else: print('The string does NOT contain any numbers')

The re.search method looks for the first location in the string where the provided regular expression produces a match.

If the re.search() method finds a match, it will return a match object, otherwise None is returned.

The first argument we passed to the re.search() method is a regular expression.

The \d character matches the digits [0-9] (and many other digit characters).

The + matches the preceding character (a digit) 1 or more times.

If you ever need help reading or writing a regular expression, consult the regular expression syntax subheading in the official docs.

The page contains a list of all of the special characters with many useful examples.

We used the match.group() method to get the entire match.

Make sure to use an if statement before calling the match.group() method. The re.search() method would return None if the string doesn't contain any numbers.

You can also use a range of digits [0-9] if you find the regular expression more readable.

main.py
import re my_str = 'bobby12hadz34.com' match = re.search(r'[0-9]+', my_str) if match: # 👇️ First number found: 12 print('First number found:', match.group()) else: print('The string does NOT contain any numbers')

The square brackets [] are used to indicate a set of characters.

The 0-9 characters match the digits in the range.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.