Isdecimal method in Python String

In this Python tutorial, I will explain what is Isdecimal method in Python string, its syntax, parameters, and return values. In the Process, we will also see some illustrative examples and How the isdecimal() string method is different from isdigit() and isnumeric() Python string methods.

Python’s built-in string method, isdecimal(), is a straightforward and effective tool that checks if all the characters in a string are decimals. This makes it a particularly valuable tool when validating data input or processing textual data in which numbers play a pivotal role.

What is the isdecimal method in Python string?

The isdecimal() method is a built-in method for string objects in Python. It returns True if all the characters in the given string are decimals (“Decimal” characters refer specifically to characters that can form numbers in the base 10 numbering system, which are 0, 1, 2, …, 9.). If the string contains any non-decimal characters, or if the string is empty, it returns False.

Syntax:

The syntax of the Python isdecimal() string method is:

string.isdecimal()

Parameter:

The Python string isdecimal method does not take any parameters.

Return values:

The Python isdecimal() method returns:

  • True: if all characters in the string are decimal characters (i.e., from 0 to 9).
  • False: otherwise (e.g., if the string contains any non-decimal characters or if the string is empty).

When to use isdecimal()

The primary use case for the isdecimal() string method in Python is to validate user input, especially when we want to ensure the entered value is a positive integer.

Let’s see some of the use cases and try to understand how the isdecimal method can be used.

Example-1: Validating the user input data with the Python isdecimal() string method

In the United States, ZIP codes are five-digit numbers. Using isdecimal(), we can easily verify if a given input data in Python is a valid ZIP code format. However, note that it won’t check the authenticity of the ZIP code, just the format.

def is_valid_zip(zip_code):
    return len(zip_code) == 5 and zip_code.isdecimal()

zip_code_1 = input('Enter the ZIP code: ')
print(is_valid_zip(zip_code_1))

zip_code_2 = input('Enter another Zip code: ')
print(is_valid_zip(zip_code_2))

The output is: In this example, zip_code_1 is a valid ZIP Code as it contains only decimal characters(0 to 9), whereas zip_code_2 contains a non-decimal character (“d”).

Enter the ZIP code: 45875
True
Enter another Zip code: 125d4
False
isdecimal python string method to validate user input data

This way we can easily identify the user input data using the isdecimal string method in Python.

Example-2: Converting Numerical Strings to Integers using the Python string isdecimal() method

Using the isdecimal() string method, we can easily avoid a ValueError when converting strings with non-decimal characters.

For instance, We are validating the price of the products from an e-commerce website on Python. Some prices are written in decimal characters and some are not. We are converting these values into integers so that the mathematical calculation should be performed on them.

def convert_price(price):
    if price.isdecimal():
        return int(price)
    else:
        print(f"Cannot convert '{price}' to an integer.")


print(convert_price("555"))
print(convert_price("11.11"))
print(convert_price("$122"))
print(convert_price("23+45"))

The output is: The string with a decimal value will be returned as an integer and for others we will get the message with the None as return value.

555
Cannot convert '11.11' to an integer.
None
Cannot convert '$122' to an integer.
None
Cannot convert '23+45' to an integer.
None
Python isdecimal string function to convert string with non decimal value

This way we can easily avoid a ValueError when converting strings with non-decimal characters using the Isdecimal function in string Python.

Differentiate between isdecimal(), isdigit() and isnumeric() methods in Python

The methods isdecimal(), isdigit(), and isnumeric() seem similar, but they have some key distinctions. Let’s dive into each one using examples and highlight these differences.

1. isdecimal()

This method returns True if all characters in a string are decimal numbers (0-9).

Example: Suppose we are developing a system for a USA shop to input products number:

Product = "8500"

if  Product.isdecimal():
    print("Valid Product number input!")
else:
    print("Invalid Product number!")

The output is: Here, isdecimal() checks if the entered Product number is purely a number between 0 and 9.

Valid Product number input!
String isdecimal method in Python

The string isdecimal method in Python.

2. isdigit()

This method returns True if all characters in a string are digits, which includes decimals and certain other characters like superscripts.

Example: Imagine a history museum in the USA displaying a presentation about the American Revolution. The presentation has footnotes with superscripted numbers to denote references.

reference = "4²"

print(reference.isdigit())
print(reference.isdecimal())

The output is: Superscript numbers aren’t decimals, but they are digits.

True
False
string isdigit comparison with string isdecimal method in Python

Comparison of isdecimal with isdigit string method in Python

3. isnumeric()

This method is the broadest among the three. It returns True if all characters in the string are numeric characters, which includes decimals, digits, and numerals from other languages or systems, such as Roman numerals or fractions.

Example: Let’s say there’s a cultural exhibition in the USA about Roman history, and attendees are asked to input Roman numerals through an interactive booth.

roman_numeral = "Ⅶ"

print(roman_numeral.isnumeric())
print(roman_numeral.isdecimal())

The Output is: Roman numerals aren’t decimals or the typical digits we think of, but they are numeric characters.

True
False
isnumeric method is compared with isdecimal string Python method

Comparison of isdecimal with isnumeric string method in Python

Conclusion

The isdecimal method in Python string offers a simple yet effective way to check for decimal characters in a Python string. While it’s a foundational check, combining it with other conditions can provide robust solutions to a variety of problems, as showcased in the examples above. We have seen how in Python isdecimal() is different from isdigit() and isnumeric() string methods.

You may also like to read: