Python isdigit() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
String

Definition

In Python, isdigit() returns True when every character is a digit and the string is not empty.

It takes no arguments. Signs, dots, letters, and spaces make it return False. Prefer isdecimal() before converting with int().

Syntax

Call isdigit on the string. Start with this line.

python
ok = text.isdigit()
CallWhat it does
"42".isdigit()Returns True.
"²".isdigit()May be True, but int("²") still fails.

Superscript digits can pass isdigit() and still fail int(). Prefer isdecimal() for int conversion.

Library declarations
python
str.isdigit() → bool

Parameters

This method has no parameters.

Return Value

Return ValueDescription
boolTrue if all characters are digits.

Python Examples

Example 1 — Basic isdigit() Checks

See what passes and what fails—including the empty string.

python
print("123".isdigit())
print("12.3".isdigit())
print("-5".isdigit())
print("".isdigit())

How It Works

  1. All digits. "123" has only digit characters → True.
  2. Dot fails. "." is not a digit → False.
  3. Sign fails. "-" is not a digit → False.
  4. Empty fails. "" is never digits → False.

Example 2 — Validate Clean Input

Strip spaces, then accept only digit strings before converting.

python
raw = "  42  "
text = raw.strip()

if text.isdigit():
    number = int(text)
    print("OK:", number)
else:
    print("Not digits only")

How It Works

  1. Clean first. strip() removes leading/trailing spaces.
  2. Gate with isdigit. Only digit-only text continues.
  3. Safe convert. int(text) is safe after a True check for ASCII digits.
  4. Reject junk. Signs, dots, or letters would take the else branch.

Example 3 — isdigit() vs isdecimal()

Superscript digits pass isdigit() but fail isdecimal().

python
s = "²"  # superscript two

print("isdigit:  ", s.isdigit())
print("isdecimal:", s.isdecimal())

How It Works

  1. Same character. Both methods inspect "²".
  2. isdigit(). Accepts some extra digit forms → True.
  3. isdecimal(). Superscripts are not decimal digits → False.
  4. Pick by goal. Broader digit check → isdigit; strict base-10 → isdecimal.

Frequently Asked Questions

It returns True if every character is a digit and the string is not empty.
No. "3.14" and "-5" both return False.
isdecimal() is stricter. isdigit() can accept some compatibility digits such as ².
It returns False.
No. It only returns a boolean.

Next: Python Interview Programs

Practice more Python problems after string validation methods.

Interview programs →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful