Python String isdecimal() Method – Tutorial with Examples

Python String isdecimal() Method

The isdecimal() method is a built-in method in Python that checks whether a string contains only decimal characters or not. A decimal character is a character in the range 0 through 9.

Syntax

The syntax of the isdecimal() method is as follows:

string.isdecimal()

Here, string is the string that we want to check for decimal characters.

Return Value

The isdecimal() method returns True if all the characters in the string are decimal characters, otherwise it returns False.

Examples

Here are three different examples of how to use the isdecimal() method in Python:

Example 1: Checking if a String Contains Only Decimal Characters

The following example demonstrates how to use the isdecimal() method to check if a string contains only decimal characters:

string = "1234"
result = string.isdecimal()
print(result)

Output:

True

In this example, we define a string “1234” and use the isdecimal() method to check whether all the characters in the string are decimal characters. Since all the characters in the string are decimal characters, the method returns True.

Example 2: Checking if a String Contains Non-Decimal Characters

The following example demonstrates how to use the isdecimal() method to check if a string contains non-decimal characters:

string = "1234abc"
result = string.isdecimal()
print(result)

Output:

False

In this example, we define a string “1234abc” and use the isdecimal() method to check whether all the characters in the string are decimal characters. Since the string contains non-decimal characters, the method returns False.

Example 3: Using the isdecimal() Method in a Loop

The following example demonstrates how to use the isdecimal() method in a loop:

strings = ["1234", "abc123", "12.34"]
for string in strings:
    result = string.isdecimal()
    print(f"{string}: {result}")

Output:

1234: True
abc123: False
12.34: False

In this example, we define a list of strings and use a loop to iterate over each string in the list. We use the isdecimal() method to check whether all the characters in each string are decimal characters. The output shows the result of the method for each string in the list.

Use Cases

The isdecimal() method can be useful in a variety of scenarios, such as:

  • Validating user input to ensure that it only contains decimal characters
  • Checking if a string is a valid integer before converting it to an integer
  • Validating input in a form to ensure that only decimal characters are entered

Overall, the isdecimal() method is a useful tool for checking whether a string contains only decimal characters or not. By using this method, you can ensure that your code only processes input that is in the correct format, which can help prevent errors and improve the overall reliability of your code.

Leave a Reply

Your email address will not be published. Required fields are marked *