Strings are used to handle text data in the python programming language. Sometimes, we need to check if a string contains a number in situations where we have to validate user input or data. In this python tutorial, we will discuss different ways to check if a given string contains a number or not.
- Check if a Python String Contains a Number Using the ord() Function
- Check if a Python String Is a Number Using the isnumeric() Method
- Verify if a Python String Contains a Number Using the isdigit() Method
- Check if a Python String Contains a Number Using the map() And the any() Function
- Check if a Python String Contains a Number Using Regular Expressions
- Conclusion
Check if a Python String Contains a Number Using the ord() Function
In ASCII encoding, numbers are used to represent characters. Each character is assigned a specific number between 0 to 127 to it. We can find the ASCII value of any number in python using the ord()
function.
The ord() function takes a character as its input argument and returns its ASCII value. You can observe this in the following python code.
zero = "0"
nine = "9"
print("The ASCII value of the character \"0\" is:", ord(zero))
print("The ASCII value of the character \"9\" is:", ord(nine))
Output:
The ASCII value of the character "0" is: 48
The ASCII value of the character "9" is: 57
As you can see in the above python program, the ASCII value for the character “0” is 48. Also, the ASCII value for the character “9” is 57. Therefore, any numeric character will have its ASCII value between 48 and 57.
We can use the ASCII values of the numeric characters to check if a string contains a number in python. For this, we will consider the string as a sequence of characters.
After that, we will follow the steps mentioned below.
- We will iterate through the characters of the original string object using a for loop and a
flag
variable. Initially, we will initialize theflag
variable to the boolean valueFalse
. - After that, we will iterate through the characters of the given input string. While iteration, we will convert each character to its ASCII numerical value.
- After that, we will check if the numeric value lies between 48 and 57 or not. If yes, the character represents a digit and hence we can say that the string contains an integer value.
- Once we find a character whose ASCII value is between 48 and 57, we will assign the boolean value
True
to theflag
variable, showing that the string contains numerical characters. Here, we have already found that the string contains a number. Therefore, we will exit from the for loop using the break statement. - If we don’t find a character that represents a digit while execution of the for loop, the
flag
variable will contain the valueFalse
.
After execution of the for loop, we will check if the flag
variable contains the value True
. If yes, we will print that the string contains a number. Otherwise, we will print that the string doesn’t contain any number. You can observe this in the following code.
myStr = "I am 23 but it feels like I am 15."
flag = False
for character in myStr:
ascii_val = ord(character)
if 48 <= ascii_val <= 57:
flag = True
break
print("The string is:")
print(myStr)
print("String contains numbers?:", flag)
Output:
The string is:
I am 23 but it feels like I am 15.
String contains numbers?: True
If you run the code given in the above example with an empty string as its input, the program works as desired. Thus, it is important to initialize the flag
variable to False
before execution of the for loop. Otherwise, the program will not work as desired.
Check if a Python String Is a Number Using the isnumeric() Method
Python provides us with different string methods with which we can check if a string contains a number or not. The isnumeric()
method, when invoked on a string, returns True
if the string consists of only numeric characters. If the string contains non-numeric characters, it returns False
.
We can check if a string contains only numeric characters or not using the isnumeric()
method as shown in the following example.
myStr1 = "123"
isNumber = myStr1.isnumeric()
print("{} is a number? {}".format(myStr1, isNumber))
myStr2 = "PFB"
isNumber = myStr2.isnumeric()
print("{} is a number? {}".format(myStr2, isNumber))
Output:
123 is a number? True
PFB is a number? False
If we are given a string containing alphanumeric characters, you can also check if the string contains numbers or not using the isnumeric()
method. For this, we will iterate through the characters of the original string object using a for loop.
- While iteration, we will invoke the
isnumeric()
method on each character. If the character represents a digit, theisnumeric()
method will returnTrue
. Hence we can say that the string contains a number. - We will assign the boolean value returned by the
isnumeric()
method to theflag
variable. - If the
flag
variable has the valueTrue
, it shows that the string contains numeric characters. Once we find that the string contains a number, we will exit from the for loop using the break statement. - If we don’t find a character that represents a digit while execution of the for loop, the
flag
variable will contain the valueFalse
.
If the flag
variable contains the value False
after the execution of the for loop, we will say the string contains numbers. Otherwise, we will say that the string does not contain numbers. You can observe this in the following code.
myStr = "I am 23 but it feels like I am 15."
flag = False
for character in myStr:
flag = character.isnumeric()
if flag:
break
print("The string is:")
print(myStr)
print("String contains numbers?:", flag)
Output:
The string is:
I am 23 but it feels like I am 15.
String contains numbers?: True
Verify if a Python String Contains a Number Using the isdigit() Method
Instead of the isnumeric()
used in the previous section, we can use the isdigit()
method to check if a string is a number or not. The isdigit()
method, when invoked on a string, returns True
if all the characters in the string are decimal digits. Otherwise, it returns False
. You can observe this in the following example.
myStr1 = "1"
isDigit = myStr1.isdigit()
print("{} is a digit? {}".format(myStr1, isDigit))
myStr2 = "A"
isDigit = myStr2.isnumeric()
print("{} is a digit? {}".format(myStr2, isDigit))
Output:
1 is a digit? True
A is a digit? False
We can also check if a string contains a number or not using the isdigit()
method. For this, we will iterate through the characters of the original string object using a for loop.
- While iteration, we will invoke the
isdigit()
method on each character. If the character represents a digit, theisdigit()
method will returnTrue
. Hence we can say that the string contains a number. - We will assign the boolean value returned by the
isdigit()
method to theflag
variable. If theflag
variable has the valueTrue
, it shows that the string contains numeric characters. - Once we find that the string contains a number, we will exit from the for loop using the break statement.
- If we don’t find a character that represents a digit while execution of the for loop, the
flag
variable will contain the valueFalse
.
If the flag
variable contains the value False
after the execution of the for loop, we will say the string contains numbers. Otherwise, we will say that the string does not contain numbers.
You can observe this in the following code.
myStr = "I am 23 but it feels like I am 15."
flag = False
for character in myStr:
flag = character.isdigit()
if flag:
break
print("The string is:")
print(myStr)
print("String contains numbers?:", flag)
Output:
The string is:
I am 23 but it feels like I am 15.
String contains numbers?: True
Check if a Python String Contains a Number Using the map() And the any() Function
In the previous sections, we have used various methods to check if a python string contains a number or not. For this, we have traversed the input string using a for loop in each of the examples. However, we can also check if the string contains a number without explicitly iterating the string. For this, we will use the map()
function.
The map()
function takes a function as its first input argument, say func
, and an iterable object say iter
as its second input argument. While execution, it executes the function func
given in the first input argument with elements of iter
as the input argument of func
. After execution, it returns a map object that contains the values returned by func
when it is executed with the elements of iter
as the input arguments.
You can convert the map object into a list using the list()
constructor.
For example, look at the following source code.
from math import sqrt
numbers = [1, 4, 9, 16, 25]
print("The numbers are:", numbers)
square_roots = list(map(sqrt, numbers))
print("The square roots are:", square_roots)
Output:
The numbers are: [1, 4, 9, 16, 25]
The square roots are: [1.0, 2.0, 3.0, 4.0, 5.0]
In the above code, we have passed the sqrt()
function as the first input argument and a list containing positive numbers as the second argument of the map()
function. After execution, we have obtained a list containing the square root of the elements of the input list.
To check if a python string contains a number or not using the map()
function, we will create a function myFunc
. The function myFunc
should take a character as its input argument. After execution, it should return True
if the character is a digit. Otherwise, it should return False
.
Inside myFunc
, we can use the isdigit()
method to check if the input character is a digit or not.
We will pass the myFunc()
function as the first argument and the input string as the second input argument to the map()
method. After execution, the map()
function will return a map object.
When we convert the map object into a list, we will get a list of boolean values True
and False
. The total number of values in the list will be equal to the number of characters in the input string. Also, each boolean value corresponds to a character at the same position in the string. In other words, the first element of the list corresponds to the first character in the input string, the second element of the list corresponds to the second character in the input string, and so on.
If there is any numeric character in the string, the corresponding element in the output list will be True
. Therefore, if the list obtained from the map object contains the value True
in at least one of its elements, we will conclude that the input string contains numbers.
To find if the output list contains the value True
as its element, we will use the any()
function.
The any()
function takes the list as its input argument and returns True
if at least one of the values is True
. Otherwise, it returns False
.
Thus, if the any()
function returns True
after execution, we will say that the input string contains a number. Otherwise, we will conclude that the input string does not contain numeric characters.
You can observe this in the following code.
def myFunc(character):
return character.isdigit()
myStr = "I am 23 but it feels like I am 15."
flag = any(list(map(myFunc, myStr)))
print("The string is:")
print(myStr)
print("String contains numbers?:", flag)
Output:
The string is:
I am 23 but it feels like I am 15.
String contains numbers?: True
This method also works well with a larger string as we don’t need to traverse the input string character by character.
Instead of defining myFunc, you can also pass a lambda function to the map() function. This will make your code more concise.
myStr = "I am 23 but it feels like I am 15."
flag = any(list(map(lambda character: character.isdigit(), myStr)))
print("The string is:")
print(myStr)
print("String contains numbers?:", flag)
Output:
The string is:
I am 23 but it feels like I am 15.
String contains numbers?: True
Instead of the isdigit()
method, you can also use the isnumeric()
method along with the map()
function and any()
function to check if a python string contains a number as shown in the following example.
def myFunc(character):
return character.isnumeric()
myStr = "I am 23 but it feels like I am 15."
flag = any(list(map(myFunc, myStr)))
print("The string is:")
print(myStr)
print("String contains numbers?:", flag)
Output:
The string is:
I am 23 but it feels like I am 15.
String contains numbers?: True
All the approaches discussed in the previous sections use standard string methods and string values. However, python also provides us with the regular expressions module ‘re’ to process textual data and strings.
Let us now discuss how we can check if a python string contains a number using the regular expressions.
Check if a Python String Contains a Number Using Regular Expressions
Regular expressions are used to manipulate text data in python. We can also use regular expressions to check if a python string contains a number or not. For this, we can use the match()
method and the search()
method. Let us discuss both these approaches one by one.
Verify if a Python String Contains a Number Using the match() Method
The match()
method is used to find the position of the first occurrence of a specific pattern in a string. It takes a regular expression pattern as its first argument and the input string as its second argument. If there exists a sequence of characters of the string that matches the regular expression pattern, it returns a match object. Otherwise, it returns None.
To check if a string contains a number using the match()
method, we will follow the following steps.
- First, we will define the regular expression pattern for numbers. As a number is a sequence of one or more numeric characters, the regular expression pattern for a number is
“\d+”
. - After defining the pattern, we will pass the pattern and the input string to the
match()
method. - If the
match()
method returnsNone
, we will say that the string doesn’t contain any number. Otherwise, we will say that the string contains numbers.
You can observe this in the following example.
import re
myStr = "23 but it feels like I am 15."
match_object = re.match(r"\d+", myStr)
print("The string is:")
print(myStr)
flag = False
if match_object:
flag = True
print("String contains numbers?:", flag)
Output:
The string is:
23 but it feels like I am 15.
String contains numbers?: True
The match()
method only works if the number is present at the beginning of the string. In other cases, it fails to check if the given string contains a number or not. You can observe this in the following example.
import re
myStr = "I am 23 but it feels like I am 15."
match_object = re.match(r"\d+", myStr)
print("The string is:")
print(myStr)
flag = False
if match_object:
flag = True
print("String contains numbers?:", flag)
Output:
The string is:
I am 23 but it feels like I am 15.
String contains numbers?: False
In the above example, you can see that the string contains numbers. However, the program concludes that there aren’t any numbers in the string. To avoid errors in checking for numbers in the string, we can use the search()
method instead of the match()
method.
Check if a Python String Contains a Number Using the search() Method
The search()
method is used to find the positions of a specific pattern in a string. It takes a regular expression pattern as its first argument and the input string as its second argument. If there exists a sequence of characters of the string that matches the regular expression pattern, it returns a match object containing the position of the first occurrence of the pattern. Otherwise, it returns None
.
To check if a string contains a number using the search()
method, we will follow all the steps that we used with the match()
method. The only difference is that we will use the search()
method instead of the match()
method. You can observe this in the following example.
import re
myStr = "I am 23 but it feels like I am 15."
match_object = re.search(r"\d+", myStr)
print("The string is:")
print(myStr)
flag = False
if match_object:
flag = True
print("String contains numbers?:", flag)
Output:
The string is:
I am 23 but it feels like I am 15.
String contains numbers?: True
The search()
method searches in the entire string. After execution, it returns a match object having the first occurrence of the input pattern. Hence, even if there is only one digit in the string, the search()
method will find that. However, this is not true for the match()
method.
Check if a Python String Contains a Number Using the findall() Method
The findall()
method is semantically similar to the search()
method. The difference is that the findall()
method returns all the occurrences of the pattern instead of the first occurrence of the pattern. When a pattern isn’t present in the input string, the findall()
method returns None
.
You can check if a python string contains a number or not using the findall()
method as shown below.
import re
myStr = "I am 23 but it feels like I am 15."
match_object = re.findall(r"\d+", myStr)
print("The string is:")
print(myStr)
flag = False
if match_object:
flag = True
print("String contains numbers?:", flag)
Output:
The string is:
I am 23 but it feels like I am 15.
String contains numbers?: True
Conclusion
In this article, we have discussed different ways to check if a python string contains a number or not. Out of all these approaches, the approach using regular expressions is most efficient. If we talk about writing more pythonic code, you can use the map()
function with the any()
function to check if a string contains a number or not. Regular expressions are a better option compared to the string methods. Hence, for the best execution times, you can use the re.search()
method to check if a string contains a number or not.
I hope you enjoyed reading this article. Stay tuned for more informative articles.
Happy Learning!
Recommended Python Training
Course: Python 3 For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.