Quite often it is necessary to know if a number is written to a variable. Such a situation may arise when processing user-entered data. When reading data from a file or processing data received from another device. In Python, checking a string for a number can be done in two ways:
- Check all characters in the string to make sure they contain digits. Usually the isdigit function is used for this.
- Try to translate the string into a number. In Python this is done using the float and int methods. In this case a possible exception is handled.
Let’s look at how these methods are used in practice.
isdigit, isnumeric, and isdecimal
Strings have an isdigit method that allows us to check if the characters that make up a string are numbers. With this method we can check if the string contains a positive integer or not. Positive is because a minus sign will not be considered a number and the method will return False.
a = '0251' print(a.isdigit()) True
If the string is empty, the function will return False.
a = '' print(a.isdigit()) False
The methods of string isnumeric and isdecimal work similarly. The only difference in these methods is the handling of special Unicode characters. Since the user will have to enter digits from 0 to 9, while we are not interested in different characters, e.g. fractions and Roman numerals, we should use the isdigit function.
Checking with Exception
What to do if you want to check a string for a negative number. In Python, you cannot use isdigit to check for negative numbers or floating point numbers. In this case, there is a universal and most reliable way. You have to cast the string to a real number. If an exception is thrown, then the string does not contain a number. Here is a function and an example of its usage:
def is_number(str): try: float(str) return True except ValueError: return False a = '123.456' print(is_number(a)) True
You can do a similar check for an integer as well:
def is_int(str): try: int(str) return True except ValueError: return False a = '123.456' print(is_int(a)) False