How to Check If a Python String Contains a Number — CODEFATHER
--
Knowing how to check if a Python string contains a number can be something you will have to do at some point in your application.
A simple approach to check if a Python string contains a number is to verify every character in the string using the string isdigit() method. Once that’s done we get a list of booleans and if any of its elements is True that means the string contains at least one number.
There are multiple ways to solve this problem and this tutorial goes through few of them.
Let’s get started!
Using a For Loop and isdigit() To Find Out if a String Contains Numbers
A basic approach to do this check is to use a for loop that goes through every character of the string and checks if that character is a number by using the string isdigit() method.
If at least one character is a digit then return True otherwise False.
We will write a function to implement this logic:
def containsNumber(value):
for character in value:
if character.isdigit():
return True
return False
The execution of the function stops as soon as the first number is found in the string or after the execution of the loop if no numbers are found.
Let’s apply this function to some strings to see if it works well:
>>> print(containsNumber('1s4f6h'))
True
>>> print(containsNumber('python'))
False
>>> print(containsNumber('python3'))
True
It’s doing its job!
Another Way To Use isdigit() to Check if a String Contains a Number
Another way to check if a Python string contains a number is by using the string isdigit() method together with a list comprehension.
Let’s recap first how the isdigit method works:
>>> '123'.isdigit()
True
>>> '1'.isdigit()
True
>>> 'a'.isdigit()
False
>>> 'a1'.isdigit()
False
>>> ''.isdigit()
False
Let’s take a string and apply isdigit() to every character of the string:
>>> value = 'adf2'
>>> [char.isdigit() for char in value]
[False, False, False, True]
We have used a list comprehension that generates a list of booleans in which every element is the value returned by isdigit() for each character in the string.
So, what can we do with this list?
We can verify if the boolean value True is in this list. This would show that the string contains at least one number.
To do that we can use an if else statement:
>>> if True in [char.isdigit() for char in value]:
… print("The string contains a number")
… else:
… print("The string doesn't contain a number")
…
The string contains a number
Let’s create a function that puts together what we have seen so far.
An if statement is used to return True if the string contains at least one number. Otherwise it returns False.
def containsNumber(value):
if True in [char.isdigit() for char in value]:
return True
return False
Here is what the function returns when we pass few strings to it:
>>> print(containsNumber(''))
False
>>> print(containsNumber('awirfd'))
False
>>> print(containsNumber('dfgh3'))
True
>>> print(containsNumber('12345'))
True
The output of our function looks good.
Using The Any() Function To Check If A String Contains a Number
We can start from the code we have created in the previous section and replace the if statement with something else…
…the Python any() built-in function that has the following syntax:
any(iterable)
The any() function returns True if any of the elements in the iterable is True, otherwise it returns False. The function also returns False if the iterable is empty.
This means that we can pass the list of booleans generated in the previous section to the any() function and remove the if statement used before:
def containsNumber(value):
return any([char.isdigit() for char in value])
As you can see we have passed a list comprehension to the any() Python function.
This is the output of our function when we pass to it the same strings tested in the previous section:
>>> print(containsNumber(''))
False
>>> print(containsNumber('awirfd'))
False
>>> print(containsNumber('dfgh3'))
True
>>> print(containsNumber('12345'))
True
Checking If a Python String Contains Numbers Using a Regular Expression
Another approach to find out if a number is part of a string is by using Python regular expressions.
The name of the Python module to handle regular expressions is re.
Firstly, let’s come up with a regular expression we can use to detect any numbers in a string. To do this we can use the re.findall() function:
re.findall(pattern, string)
The first argument we pass to re.findall is the pattern we are looking for.
To look for more than one number we can use ‘[0–9]+’.
The second argument is the string in which we look for the specific pattern.
Here is the output of this regular expression applied to multiple strings:
>>> print(re.findall('[0-9]+', ''))
[]
>>> print(re.findall('[0-9]+', 'awirfd'))
[]
>>> print(re.findall('[0-9]+', 'dfgh3'))
['3']
>>> print(re.findall('[0-9]+', '12345'))
['12345']
>>> print(re.findall('[0-9]+', '12az3dr45'))
['12', '3', '45']
We can update our function to call re.findall() and check if the resulting list is empty or not.
If the resulting list is not empty then the string contains at least one number. We can also use the fact that in Python empty sequences are false.
import redef containsNumber(value):
numbers = re.findall('[0-9]+', value)
return True if numbers else False
The return statement of this function uses the Python ternary operator to return True or False depending on the fact that the numbers list is empty or not.
Another option is to use the bool() function to convert the list returned by the re.findall() function into a boolean:
import redef containsNumber(value):
return bool(re.findall('[0-9]+', value))
Let’s apply this function to few strings to confirm it works as expected:
>>> print(containsNumber(''))
False
>>> print(containsNumber('awirfd'))
False
>>> print(containsNumber('dfgh3'))
True
>>> print(containsNumber('12345'))
True
>>> print(containsNumber('12as34rt5'))
True
How Do You Check If String Contains Number Using the Map Function?
And here is another way to find out if there are any numbers in your string.
This time we will use the map() function that applies a specific function to the elements of an iterable (a string is an iterable because you can see it as a sequence of characters).
If we pass the isdigit() function and a string to the map function we get back a map object.
>>> map(str.isdigit, '12r45')
<map object at 0x7f9e88295190>
What can we do with it?
We can use the list() function to convert it into a Python list:
>>> list(map(str.isdigit, '12r45'))
[True, True, False, True, True]
As you can see from the output above we get back a list of booleans where every boolean is related to a character in the string. The boolean is True if the character is a number and it’s False otherwise.
We can then use the any() function, already used in one of the previous sections, to know if the list contains at least one True element.
>>> any(map(str.isdigit, '12r45'))
True
>>> any(map(str.isdigit, 'etdgr'))
False
Makes sense?
Conclusion
We have gone through multiple ways to find out if a Python string contains a number.
You have learned how to use the string isdigit() method, the any() function, regular expressions and the map function.
What is your favourite way? Do you suggest any other approaches?
Let me know in the comments below :)
Originally published at https://codefather.tech on May 29, 2021.