Python comes with three different methods that let you check if a string is a numeric. In this post, you’ll learn the subtle differences between isdigit
, isnumeric
, and isdecimal
. There are subtle, but important differences between the methods, and knowing them is important to understand which one is best one for the job. While on the surface, they may look like they’ll all accomplish the same thing, you’ll save yourself a ton of headaches in your programming.
After reading this post, you’ll have learned:
- What the
.isdigit()
,.isnumeric()
, and.isdecimal()
methods do, what their limitations are, and what the best use cases for each are and - The differences between the three methods and when some may not work as you’d expect.
The Quick Answer: A Summary of the Methods
String Type | Example | Python .isdecimal() | Python .isdigit() | Python .isnumeric() |
---|---|---|---|---|
Base 10 Numbers | '0123' | True | True | True |
Fractions and Superscripts | '⅔', '2²' | False | True | True |
Roman Numerals | 'ↁ' | False | False | True |
.isdecimal()
, .isdigit()
, and .isnumeric()
methodsTable of Contents
Python isdigit: How it works
The Python isdigit
method returns True
is all the characters in a string are digits, and False
if not.
Let’s try out a few different examples to see how the method works before diving into some of its nuances:
# Python .isdigit() to check if all characters are digits
# If all characters are digits, .isdigit() returns True
>>> '123'.isdigit()
True
# If not all characters are digits, .isdigit() returns False
>>> '123abc'.isdigit()
False
# If there's whitespace, .isdigit() returns False
>>> ' 123'.isdigit()
False
# If there's decimals, .isdigit() returns False
>>> '1.23'.isdigit()
False
You can see from the examples above that the Python isdigit
method has some nuances. Specifically, the method works with these different characteristics:
- If all characters are digits, the method returns
True
- If a character is a whitespace or a decimal, the method returns
False
Some interesting notes about the Python isdigit method is that it also works with superscripts and with exponents (superscript characters), even when they’re formatted in their unicode versions.
Let’s see what this looks like:
# Python isdigit works with exponents
# Load the value for a cubed exponent
>>> cubed = "\u00B2"
# Check if it's a digit using Python .isdigit()
>>> cubed.isdigit()
True
While it may appear that the string contains non-digit characters, once Python interprets the string from its unicode version, Python is able to determine that the string, in fact, only contains digits.
In the next section, you’ll learn about the Python isnumeric
method which will allows you to check if a string contains numeric values.
Want to learn more about Python for-loops? Check out my in-depth tutorial that takes your from beginner to advanced for-loops user! Want to watch a video instead? Check out my YouTube tutorial here.
Python isnumeric: How it works
The Python isnumeric
method has a number of key differences between the Python isdigit method. While the isidigit
method checks whether the string contains only digits, the isnumeric
method checks whether all the characters are numeric.
This is the key difference: the isnumeric
method is able to handle items such as unicode fractions and Roman numerals, as long as all the characters in the string are numeric-like values.
That is to say, that the isdigit
method checks whether a character is a unicode representation of a digit, while isnumeric
method checks if a the character is a unicode representation of a numeric value.
Let’s see how we can use the Python isnumeric
method works:
# Python isnumeric to check if characters are numeric values
# Check if a string containing an integer is numeric
>>> integer = '2'
>>> print(f'{integer.isnumeric()=}')
integer.isnumeric()=True
# Check if a string containing a float is numeric
>>> floats = '2.3'
>>> print(f'{floats.isnumeric()=}')
floats.isnumeric()=False
# Check if a string containing a fraction is numeric
>>> fraction = '⅔'
>>> print(f'{fraction.isnumeric()=}')
fraction.isnumeric()=True
# Check if a string containing an exponent is numeric
>>> exponent = '2²'
>>> print(f'{exponent.isnumeric()=}')
exponent.isnumeric()=True
We can see here that when we pass in a string containing numeric type values (and only numeric type values) that the isnumeric
method returns True
.
The distinction made above is important. The reason the fraction we passed in returned True
is because it was the unicode representation of the fraction. If we had created a fraction merely as a string, then the method would return False
.
We can confirm this below:
# Representing a fraction as a unicode
>>> unicode_fraction = '⅔'
>>> print(f'{unicode_fraction.isnumeric()=}')
unicode_fraction.isnumeric()=True
# Representing a fraction without unicode representation
>>> string_fraction = '2/3'
>>> print(f'{string_fraction.isnumeric()=}')
string_fraction.isnumeric()=False
We can see here, that because the string fraction contains a /
, that not all the characters are numeric, and False
is returned.
Finally, let’s see how this works for Roman numerals. We’ll load a Roman numeral using a unicode representation and directly as a string:
# Check if a roman numeral is considered numeric
>>> roman_numeral = 'ↁ'
>>> print(f'{roman_numeral.isnumeric()=}')
roman_numeral.isnumeric()=True
In the next section, you’ll learn how to use the Python isdecimal
method.
Want to learn how to get a file’s extension in Python? This tutorial will teach you how to use the os and pathlib libraries to do just that!
Python isdecimal: How it works
The Python isdecimal
method is a bit different, in that it evaluates whether a character is a decimal character, rather than a numeric character. Because of this, it will only return True
if all the characters can evaluate to a base ten number, meaning that fractions and superscripts will return False
.
Let’s take a look at the same examples as above and see what the isdecimal
method returns:
# Python isdigit to check if characters are digit values
# Check if a string containing an integer is a decimal
>>> integer = '2'
>>> print(f'{integer.isdecimal()=}')
integer.isdecimal()=True
# Check if a string containing a float is a decimal
>>> floats = '2.3'
>>> print(f'{floats.isdecimal()=}')
floats.isdecimal()=False
# Check if a string containing a fraction is a decimal
>>> fraction = '⅔'
>>> print(f'{fraction.isdecimal()=}')
fraction.isdecimal()=False
# Check if a string containing an exponent is a decimal
>>> exponent = '2²'
>>> print(f'{exponent.isdecimal()=}')
exponent.isdecimal()=False
We can see here that the isdecimal
method is quite explicit about what it considers as decimals. This can be very helpful when you only want to return base-10 values.
Want to learn how to pretty print a JSON file using Python? Learn three different methods to accomplish this using this in-depth tutorial here.
Differences between Python isdigit, isnumeric, isdecimal
The table below breaks down the key differences between the isdigit
, isnumeric
, and isdecimal
methods, which can be used to identify differences related to numbers in Python strings.
One thing to note here is that: the truthy-ness evaluates in order of isdecimal
, isdigit
, then isnumeric
– meaning that anything that is True for isdecimal is for the following two. Anything that is True for isdigit is True for isnumeric.
String Type | Example | Python .isdecimal() | Python .isdigit() | Python .isnumeric() |
---|---|---|---|---|
Base 10 Numbers | '0123' | True | True | True |
Fractions and Superscripts | '⅔', '2²' | False | True | True |
Roman Numerals | 'ↁ' | False | False | True |
.isdecimal()
, .isdigit()
, and .isnumeric()
methodsWhile this table provides a simplified, high-level overview of the methods, the sections above provide a much more nuanced look into how the methods work and what types of results to expect.
Want to learn more about calculating the square root in Python? Check out my tutorial here, which will teach you different ways of calculating the square root, both without Python functions and with the help of functions.
How to Check If a Float is a Numeric
The easiest way to check if a string representation of a float is numeric is to use the float()
function. If the function does not raise a ValueError
, then the string represents a float.
This isn’t always the most intuitive way of doing this is to develop a function that accomplishes this. The added benefit of this is that we can return a boolean value, which will not break out program.
Let’s see how we can develop a Python function to check if a string representing a float is numeric:
# Check if a string represents a float in Python
def is_float(a_string):
try:
float(a_string)
return True
except ValueError:
return False
print(is_float('2.2.2'))
print(is_float('2.123'))
# Returns:
# False
# True
We can see here that when a string with incorrect float types are passed in, False
is returned. If the string does represent a float, then True
is returned.
In the next section, you’ll learn how to work with negative numbers to identify if they represent numeric types.
Want to learn more about Python f-strings? Check out my in-depth tutorial, which includes a step-by-step video to master Python f-strings!
How to Check if a Negative Number is Numeric
All of the different methods described above will not work with negative numbers. This is because the negative sign, -
, will return False
. Because of this, the best way to check this is to remove the negative symbol from the string if it’s the first character.
Let’s see how we can develop a function that checks this.
# A function to check if a digit string using a negative number
def is_negative_digit(a_string):
if a_string[0] == '-':
return a_string[1:].isdigit()
print(is_negative_digit('-123.3'))
print(is_negative_digit('-123'))
# Returns:
# False
# True
We can see here that the function works as expected, by first stripping the first character if it’s equal to -
.
Want to learn how to calculate and use the natural logarithm in Python. Check out my tutorial here, which will teach you everything you need to know about how to calculate it in Python.
Conclusion
In this post, you learned how to use the Python string methods isdigit
, isnumeric
, and isdecimal
to check whether or not a string represents different numerical types. You learned the subtle differences between the three methods, giving you a string understanding of when to use each of the methods (and, importantly, when not to). You also learned how to work with strings representing floats and strings representing negative numbers.
To learn more about the Python isdigit
method, check out the official documentation here. The official documentation for isnumeric
can be found here, and the documentation for isdecimal
can be found here.
While the isidit method checks whether the string contains only digits,
to correct:
While the isidigit method checks whether the string contains only digits,
Thanks so much, Rolf! I have updated the article.
bruh, there’s no need to format a string if all you’re putting in it a a number.
Bad:
print(f'{num}’)
Good:
print(num)
oh nvm, I see what you’re doing. i would delete the comment but I don’t think there’s a way.
Thanks Henry!
Obrigado pelas informações!
De nada, Ezac!
.isdigit() is not applicable on fractions, i have executed it in IDLE