Check if a string contains only Numbers in Python

avatar

Borislav Hadzhiev

Last updated: Sep 19, 2022

banner

Photo from Unsplash

Check if a string contains only Numbers in Python #

Use the str.isnumeric() method to check if a string contains only numbers, e.g. if string.isnumeric():. The str.isnumeric() method will return True if all characters in the string are numeric, otherwise False is returned.

main.py
import re # ✅ Check if string contains only numbers (str.isnumeric()) 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 (re.match()) # 👇️ <re.Match object; span=(0, 7), match='3468910'> print(re.match(r'^[0-9]+$', my_str)) if re.match(r'^[0-9]+$', my_str): # 👇️ this runs print('The string contains only numbers') else: print('The string does NOT contain only numbers')

The first example uses the str.isnumeric() method to check if a string contains only numbers.

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

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.

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

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

Use the re.match() method to check if a string contains only numbers, e.g. re.match(r'^[0-9]+$', string). 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 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 bool() class takes a value and converts it to a boolean (True or False).

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.