Check if a String contains a Number in Python

avatar
Borislav Hadzhiev

Last updated: Apr 9, 2024
5 min

banner

# Table of Contents

  1. Check if a string contains a Number in Python
  2. Check if a string contains ONLY Numbers in Python

# Check if a string contains a number in Python

To check if a string contains a number in Python:

  1. Use a generator expression to iterate over the string.
  2. Use the str.isdigit() method to check if each char is a digit.
  3. Pass the result to the any() function.
  4. The any function will return True if the string contains a number.
main.py
def contains_number(string): return any(char.isdigit() for char in string) print(contains_number('abc123')) # ๐Ÿ‘‰๏ธ True print(contains_number('abc')) # ๐Ÿ‘‰๏ธ False print(contains_number('-1abc')) # ๐Ÿ‘‰๏ธ True if contains_number('abc123'): # ๐Ÿ‘‡๏ธ This runs print('The string contains a number') else: print('The string does NOT contain a number') # ----------------------------- # โœ… Check if a string contains a specific number print('123' in 'abc123') # ๐Ÿ‘‰๏ธ true print('567' in 'abc123') # ๐Ÿ‘‰๏ธ False

check if string contains number

The code for this article is available on GitHub
If you'd rather use a regular expression, scroll down to the next subheading.

We used a generator expression to iterate over the string.

Generator expressions are used to perform some operation for every element or select a subset of elements that meet a condition.

On each iteration, we use the str.isdigit() method to check if the character is a digit.

The str.isdigit() method returns True if all characters in the string are digits and there is at least 1 character, otherwise False is returned.

The last step is to pass the generator object to the any() function.

main.py
def contains_number(string): return any(char.isdigit() for char in string) print(contains_number('abc123')) # ๐Ÿ‘‰๏ธ True print(contains_number('abc')) # ๐Ÿ‘‰๏ธ False print(contains_number('-1abc')) # ๐Ÿ‘‰๏ธ True

The any function takes an iterable as an argument and returns True if any element of the iterable is truthy.

The any() function will return True if at least 1 character in the string is a number.

If you need to check if a string contains a specific number, use the in operator.

main.py
print('123' in 'abc123') # ๐Ÿ‘‰๏ธ True print('567' in 'abc123') # ๐Ÿ‘‰๏ธ False

The in operator tests for membership. For example, x in s evaluates to True if x is a member of s, otherwise it evaluates to False.

# Check if a string contains a number using a for loop

You can also use a for loop to check if a string contains a number.

main.py
def contains_number(string): for char in string: if char.isdigit(): return True return False print(contains_number('abc123')) # ๐Ÿ‘‰๏ธ True print(contains_number('abc')) # ๐Ÿ‘‰๏ธ False print(contains_number('-1abc')) # ๐Ÿ‘‰๏ธ True if contains_number('abc123'): # ๐Ÿ‘‡๏ธ This runs print('The string contains a number') else: print('The string does NOT contain a number')

check if string contains number using for loop

The code for this article is available on GitHub

The for loop iterates over the string and checks if each character is a number using the isdigit() method.

# Check if a string contains a number using re.search()

This is a two-step process:

  1. Use the re.search() method to check if the string contains any digits.
  2. Use the bool() class to convert the output from re.search to a boolean.
main.py
import re def contains_number(string): return bool(re.search(r'\d', string)) print(contains_number('abc123')) # ๐Ÿ‘‰๏ธ True print(contains_number('abc')) # ๐Ÿ‘‰๏ธ False print(contains_number('-1abc')) # ๐Ÿ‘‰๏ธ True

check if string contains number using re search

The code for this article is available on GitHub

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 any digits, it will return amatch object, otherwise None is returned.

The first argument we passed to the method is a regular expression.

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

If the string contains any digits, the re.search method will return a match object, which when converted to boolean returns True.

main.py
# ๐Ÿ‘‡๏ธ <re.Match object; span=(3, 4), match='1'> print(re.search(r'\d', 'abc123')) # ๐Ÿ‘‡๏ธ None print(re.search(r'\d', 'abc'))

If the pattern is not matched in the string, the method returns None, which is a falsy value.

An alternative to using the \d character is to specify a set of digits [0-9].

main.py
import re def contains_number(string): return bool(re.search(r'[0-9]', string)) print(contains_number('abc123')) # ๐Ÿ‘‰๏ธ True print(contains_number('abc')) # ๐Ÿ‘‰๏ธ False print(contains_number('-1abc')) # ๐Ÿ‘‰๏ธ True

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

In the case of [0-9], the pattern matches any digit.

# Check if a string contains a number using re.findall()

Alternatively, you can use the re.findall() method.

main.py
import re my_str = 'a12b34c56' matches = re.findall(r'\d+', my_str) print(matches) # ๐Ÿ‘‰๏ธ ['12', '34', '56'] if len(matches) > 0: print('The string contains a numebr') else: print('The string does NOT contain a number')

check if string contains number using re findall

The code for this article is available on GitHub

The re.findall() method takes a pattern and a string as arguments and returns a list of strings containing all non-overlapping matches of the pattern in the string.

If the list of matches has a length greater than 0, then the string contains at least 1 number.

# Check if a string contains only Numbers in Python

You can use the str.isnumeric() method to check if a string contains only numbers.

main.py
import re my_str = '3468910' print(my_str.isnumeric()) # ๐Ÿ‘‰๏ธ True if my_str.isnumeric(): # ๐Ÿ‘‡๏ธ This runs print('The string contains only numbers') else: print('The string does NOT contain only numbers')

check if string contains only numbers

The code for this article is available on GitHub

The str.isnumeric() method returns True if all characters in the string are numeric, and there is at least one character, otherwise False is returned.

main.py
print('5'.isnumeric()) # ๐Ÿ‘‰๏ธ True print('50'.isnumeric()) # ๐Ÿ‘‰๏ธ True print('-50'.isnumeric()) # ๐Ÿ‘‰๏ธ False print('3.14'.isnumeric()) # ๐Ÿ‘‰๏ธ False print('A'.isnumeric()) # ๐Ÿ‘‰๏ธ False

Notice that the str.isnumeric() method returns False for negative numbers (they contain a minus) and for floats (they contain a period).

Use a try/except statement if you need to check if a string is a valid integer or a valid floating-point number.
main.py
# โœ… Check if a string is a valid integer def is_integer(string): try: int(string) except ValueError: return False return True print(is_integer('359')) # ๐Ÿ‘‰๏ธ True print(is_integer('-359')) # ๐Ÿ‘‰๏ธ True print(is_integer('3.59')) # ๐Ÿ‘‰๏ธ False print(is_integer('3x5')) # ๐Ÿ‘‰๏ธ False # ---------------------------------------------- # โœ… Check if a string is a valid float def is_float(string): try: float(string) except ValueError: return False return True print(is_float('359')) # ๐Ÿ‘‰๏ธ True print(is_float('-359')) # ๐Ÿ‘‰๏ธ True print(is_float('3.59')) # ๐Ÿ‘‰๏ธ True print(is_float('3x5')) # ๐Ÿ‘‰๏ธ False
The code for this article is available on GitHub

If converting the string to an integer or float fails, the except block runs where we handle the ValueError by returning False from the function.

# Check if a string contains only Numbers using re.match()

Alternatively, you can use the re.match() method.

The re.match() method will return a match object if the string contains only numbers, otherwise None is returned.

main.py
import re def only_numbers(string): return re.match(r'^[0-9]+$', string) # ๐Ÿ‘‡๏ธ <re.Match object; span=(0, 4), match='3590'> print(only_numbers('3590')) if only_numbers('3590'): # ๐Ÿ‘‡๏ธ this runs print('The string contains only numbers') else: print('The string does NOT contain only numbers')
The code for this article is available on GitHub

The re.match() method returns a match object if the provided regular expression is matched in the string.

The match() method returns None if the string doesn't match the regex pattern.

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

main.py
import re def only_numbers(string): return re.match(r'^[0-9]+$', string)

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

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

The caret ^ matches the start of the string and the dollar sign $ matches the end of the string.

The plus + causes the regular expression to match 1 or more repetitions of the preceding character (the range of numbers).

If you want to return a boolean result from the function, pass the call to re.match() to the bool() class.

main.py
import re def only_numbers(string): return bool(re.match(r'^[0-9]+$', string)) print(only_numbers('3590')) # ๐Ÿ‘‰๏ธ True print(only_numbers('3x59')) # ๐Ÿ‘‰๏ธ False if only_numbers('3590'): # ๐Ÿ‘‡๏ธ this runs print('The string contains only numbers') else: print('The string does NOT contain only numbers')
The code for this article is available on GitHub

The bool() class takes a value and converts it to a boolean (True or False).

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.

Copyright ยฉ 2024 Borislav Hadzhiev