str.isdigit()

Are these all digits? The pre-flight check before int() — with edge cases worth knowing.

String methodPython 2.0+Live demo
Common call
user_input.isdigit()
Returns
bool — empty string is False
Replaces
no sign, no decimal point: "-3" and "1.5" are False
Watch out
passing isdigit does not guarantee int() semantics you expect — "0010" passes
str.isdigit()
bool

Demo

Live evaluation
Try:
Inputs
stringstrthe source
Output
'12345'.isdigit()
True

True only when every character is a digit and there is at least one. Signs, decimal points, spaces — anything non-digit — make it False. (Full Python also accepts some Unicode digit characters like ²; this demo covers the ASCII cases.)

Common patterns

Validate before converting
The classic guard for user input destined for int().
if age.isdigit():
    age = int(age)
Filter numeric tokens
Keep only all-digit pieces of a split.
numbers = [t for t in tokens if t.isdigit()]

Examples

1. All digits
"12345".isdigit()
Returns
True
2. Decimal point
"1.5".isdigit()
Returns
False
3. Negative sign
"-3".isdigit()
Returns
False
4. Empty string
"".isdigit()
Returns
False

Pitfalls

1. Signed and decimal numbers fail
isdigit validates digits only — not "parseable as a number".
Rejected
"-3".isdigit() or "1.5".isdigit()
False
Parse-and-catch instead
try:
    x = float(s)
except ValueError:
    ...
handles signs, decimals, exponents
2. isdigit vs isnumeric vs isdecimal
Three similar methods differ on Unicode: isdecimal ⊂ isdigit ⊂ isnumeric.
Which one?
"²".isdigit(), "½".isnumeric()
(True, True) — but int("²") raises!
Strictest for int()
s.isdecimal()  # only characters int() accepts
safe pre-check

When to use

Use it
  • Quick guard on simple non-negative integer input
  • Filtering all-digit tokens
Reach for something else
  • Signs / decimals / exponents → try/except around int() or float()
  • Exact int()-compatibility → str.isdecimal
  • Any Unicode numeral counts → str.isnumeric

Notes

Complexity
O(n)
Return
bool
CPython impl
Objects/unicodeobject.c :: unicode_isdigit
Memory
No allocation
Thread-safe
Yes — str is immutable

FAQ

All the is* string methods require at least one character — an empty string has nothing to be "all digits".

History

2.0
Method available on the unified string type.