Python String isdigit()


Python String isdigit() method

Python String isdigit() method is used to check if all characters in the string are digits and there is at least one character in the string.

Consider that given string is in x.

x = "12345"

Then the return value of x.isdigit() is

True

In this tutorial, you will learn the syntax and usage of String isdigit() method in Python language.

Syntax of isdigit() method

The syntax of String isdigit() method in Python is given below.

str.isdigit()

Parameters

The string isdigit() method takes no parameters.

Return value

The string isdigit() method returns a boolean value of True if all characters in the string are digits and there is at least one character in the string, otherwise False.

Examples

1. Checking if given string has only digits in Python

In this example, we take a string value in variable x. We have to check if all characters in the string are digits.

Call isdigit() method on the string object x and use the returned value as a condition in Python if else statement as shown in the following program.

Since all characters in the given string x are digits, isdigit() method returns True, and the if-block executes.

Python Program

x = "12345"

if x.isdigit():
    print('Given string is DIGIT.')
else:
    print('Given string is NOT DIGIT.')

Output

Given string is DIGIT.

2. isdigit() with string containing special symbols in Python

In the following program, we take a string value in variable x such that some of the characters in the string are not digits like +, $, etc.

Since, not all characters in the string are digits, isdigit() method returns False, and the else-block executes.

Python Program

x = "$12345+89"

if x.isdigit():
    print('Given string is DIGIT.')
else:
    print('Given string is NOT DIGIT.')

Output

Given string is NOT DIGIT.

3. isdigit() with an empty string

In the following program, we take an empty string value in variable x, and check the return value of isdigit() for this empty string.

Python Program

x = ""

if x.isdigit():
    print('Given string is DIGIT.')
else:
    print('Given string is NOT DIGIT.')

Output

Given string is NOT DIGIT.

Summary

In this tutorial of Python String Methods, we learned about String isdigit() method, its syntax, and examples.