Easy Tutorial
❮ Python Os Mkdir Python Random Number ❯

Python3 isdigit() Method

Python3 String


Description

The Python isdigit() method checks if the string consists only of digits.

Syntax

The syntax for the isdigit() method is:

str.isdigit()

Parameters

Return Value

Returns True if the string contains only digits, otherwise returns False.

Example

The following example demonstrates the use of the isdigit() method:

#!/usr/bin/python3

str = "123456"; 
print (str.isdigit())

str = "tutorialpro example....wow!!!"
print (str.isdigit())

The output of the above example is:

True
False

The isdigit() method works correctly only for positive integers. It does not correctly identify negative numbers or decimals.

The following function can be used to address this:

# Check if a string is a number
def is_number(s):    
    try:    # If the float(s) statement can be executed, return True (string s is a float)        
        float(s)        
        return True    
    except ValueError:  # ValueError is a standard Python exception indicating an "invalid parameter"        
        pass  # If a ValueError exception is raised, do nothing (pass: do nothing, usually used as a placeholder statement)    
    try:        
        import unicodedata  # Package for handling ASCII codes        
        unicodedata.numeric(s)  # Function to convert a numeric string to a float        
        return True    
    except (TypeError, ValueError):        
        pass    
        return False

print(is_number(1))
print(is_number(1.0))
print(is_number(0))
print(is_number(-2))
print(is_number(-2.0))
print(is_number("abc"))

The output is:

True
True
True
True
True
False

Python3 String

❮ Python Os Mkdir Python Random Number ❯