Strings can contain all kinds of text: numbers, alphabets, Roman numerals, even hexadecimal values. But what if you needed to know whether or not a string only contains numbers? This can be done using the isdigit()
built-in method in Python. The illustration below shows how the isdigit()
method works.
Now that we know what this method does, let’s look at its signature.
This is an in-built method of strings and does not require any parameter to be passed.
It returns a boolean value of true
or false
depending on if the string only contains digits and is not empty.
Note: The method does not recognize currency values, fractions, or Roman numerals as digits.
The code snippet below shows how to call this method. str
is the string on which the method is called.
str.isdigit()
Now that we know how this method works, let’s see how we can use it.
# This should return true as the string only contains integersnumeric_str = "101202303"print(numeric_str.isdigit())# This should return false as the string contains alphabetsalphanumeric_str = "10120A2303"print(alphanumeric_str.isdigit())# This should return false as the string contains the dollar currency signcurrency_str = "$10"print(currency_str.isdigit())# This should return false as the string is a fractionfraction_str = "2/3"print(fraction_str.isdigit())
Free Resources