How to Check if there are Numbers in Strings in Python
Determining if a string contains numeric characters is a common task in Python.
This guide demonstrates various methods for checking if a string contains numbers, whether it contains only numbers, including techniques using generator expressions, regular expressions, string methods and built-in functions.
Checking if a String Contains a Number
Several approaches can be used to determine if a string contains any digits.
Using a Generator Expression and any()
This method combines a generator expression with the any()
function for a concise solution:
def contains_number(string):
return any(char.isdigit() for char in string)
print(contains_number('abc123')) # Output: True
print(contains_number('abc')) # Output: False
print(contains_number('-1abc')) # Output: True
- The
isdigit()
method checks if all characters in a string are digits. Returns True if the string contains only digits and is not empty, otherwise returns False.
Using a for
Loop
A for
loop provides a more explicit approach:
def contains_number_loop(string):
for char in string:
if char.isdigit():
return True # Return True immediately if digit found
return False # Return False if no digits found after loop
print(contains_number_loop('abc123')) # Output: True
print(contains_number_loop('abc')) # Output: False
print(contains_number_loop('-1abc')) # Output: True
- The function iterates over the characters and immediately returns
True
if a digit is encountered. - If no digits are present it returns
False
.
Using re.search()
The re.search()
method, which uses regular expressions, provides a more flexible approach that allows for looking for more complex patterns, and can also match multiple different digits at once:
import re
def contains_number_regex(string):
return bool(re.search(r'\d', string))
print(contains_number_regex('abc123')) # Output: True
print(contains_number_regex('abc')) # Output: False
print(contains_number_regex('-1abc')) # Output: True
re.search(r'\d', string)
returns a match object if a digit is found, andNone
if not found, which thenbool()
casts to True or False respectively.
Using re.findall()
The re.findall()
method finds all occurrences of the pattern and returns a list of matches. This method is especially useful when there are multiple matches:
import re
my_str = 'a12b34c56'
matches = re.findall(r'\d+', my_str) # r'\d+' matches one or more consecutive digits.
print(matches) # Output: ['12', '34', '56']
if len(matches) > 0:
print('The string contains a number') # Output: The string contains a number
else:
print('The string does NOT contain a number')
Checking if a String Contains Only Numbers
To ensure a string only contains numbers, use the isnumeric()
method, try/except
or a regular expression.
Using isnumeric()
The isnumeric()
method is a direct way to check for numeric characters, including digits and other Unicode numeric characters. It does not, however, include characters like -
or .
.
my_str = '3468910'
print(my_str.isnumeric()) # Output: True
if my_str.isnumeric():
print('The string contains only numbers') # Output: The string contains only numbers
else:
print('The string does NOT contain only numbers')
print('5'.isnumeric()) # Output: True
print('-50'.isnumeric()) # Output: False
print('3.14'.isnumeric()) # Output: False
Validating Integers and Floats with try
/except
If you need to determine that the string is a valid number use a try/except block to handle potential ValueError
during casting.
# 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')) # Output: True
print(is_integer('-359')) # Output: True
print(is_integer('3.59')) # Output: 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')) # Output: True
print(is_float('-359')) # Output: True
print(is_float('3.59')) # Output: True
- The functions attempt to cast the string using either
int()
orfloat()
. - The
try/except
block gracefully handles invalid strings, preventing errors and returningFalse
in such cases.
Using re.match()
A more direct way to validate that a string consists only of digits is using regular expressions:
import re
def contains_only_numbers(string):
return bool(re.match(r'^[0-9]+$', string))
print(contains_only_numbers('3590')) # Output: True
print(contains_only_numbers('3x59')) # Output: False
- The regex pattern
^[0-9]+$
matches a string containing one or more digits from start (^
) to end ($
) of the string, effectively checking that it contains only numbers.