Skip to content

isdigit function in Python

In Python, the isdigit() method is a built-in string method that checks whether all the characters in a given string are digits (numeric characters). It returns True if all characters in the string are digits, and False otherwise.

Here’s the basic syntax of the isdigit() method:

string.isdigit()
  • str: This is a string object (or a variable containing a string) on which you want to apply the isdigit() method.

You call the isdigit() method on a string, and it returns a Boolean value (True or False) based on whether all the characters in the string are digits or not.

isdigit function in Python example

Here’s an example of how to use the isdigit() method:

# Example 1: Using isdigit() with a string containing only digits
num_str1 = "12345"
result1 = num_str1.isdigit()
print(result1)  # Output: True

# Example 2: Using isdigit() with a string containing both digits and non-digits
mixed_str = "12345abc"
result2 = mixed_str.isdigit()
print(result2)  # Output: False

More example

# Example 1: Using isdigit() with a string containing only digits
num_str1 = "12345"
if num_str1.isdigit():
    print(f"'{num_str1}' consists of only digits.")
else:
    print(f"'{num_str1}' does not consist of only digits.")

# Example 2: Using isdigit() with a string containing both digits and non-digits
mixed_str = "12345abc"
if mixed_str.isdigit():
    print(f"'{mixed_str}' consists of only digits.")
else:
    print(f"'{mixed_str}' does not consist of only digits.")

Output:

isdigit function in Python

In this example, we have two strings:

  1. num_str1 contains only digits, so isdigit() returns True, and the first condition is met, printing that it consists of only digits.
  2. mixed_str contains both digits and non-digits, so isdigit() returns False, and the second condition is met, printing that it does not consist of only digits.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

2 thoughts on “isdigit function in Python”

Leave a Reply

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