Last updated: Apr 9, 2024
Reading timeยท5 min
To check if a string contains a number in Python:
str.isdigit()
method to check if each char is a digit.any()
function.any
function will return True
if the string contains a number.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
We used a generator expression to iterate over the string.
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.
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.
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.
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
.
for
loopYou can also use a for loop to check if a string contains a number.
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')
The for
loop iterates over the string and checks if each character is a number
using the isdigit()
method.
This is a two-step process:
re.search()
method to check if the string contains any digits.bool()
class to convert the output from re.search
to a boolean.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
The re.search() method looks for the first location in the string where the provided regular expression produces a match.
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
.
# ๐๏ธ <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]
.
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.
Alternatively, you can use the re.findall()
method.
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')
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.
You can use the str.isnumeric()
method to check if a string contains only
numbers.
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')
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.
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).
try/except
statement if you need to check if a string is a valid integer or a valid floating-point number.# โ 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.
The re.match()
method will return a match
object if the string contains only
numbers, otherwise None
is returned.
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.
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.
^
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.
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).
You can learn more about the related topics by checking out the following tutorials: