isdigit Versus isdecimal For Numeric Input

isdigit accepts superscripts and other non-decimal digits, so input validation that feeds int() must gate on isdecimal instead of isdigit.

PythonData Integrity

Code

pythonsnippet
20 lines
candidates = ["42", "42.5", " 42", "-1", "²", "½", "Ⅳ", "٤"]

for text in candidates:
    print(repr(text), "| isdigit:", text.isdigit(), "isdecimal:", text.isdecimal(), "isnumeric:", text.isnumeric())

# only isdecimal True marks decimal digits with the same semantics as int()
decimal_only = [t for t in candidates if t.isdecimal()]
print("decimal only:", decimal_only)

# the is* checks require the whole string to qualify: a minus sign or decimal point makes the whole thing False
print("'-1'.isdecimal():", "-1".isdecimal(), "| '42.5'.isdecimal():", "42.5".isdecimal())

# int() itself accepts every decimal digit form: Arabic-Indic digits convert directly too
print("int('٤'):", int("٤"))

# but superscript ² is not a decimal digit: int() rejects it as well
try:
    int("²")
except ValueError as exc:
    print("int('²') raises:", exc)

How the snippet works

The one repetition in this snippet is the loop for text in candidates.

Module-level bindings hold the data — candidates, decimal_only — with no function scope in between.

Applying it

The demo output is labeled (decimal only:, int(), so every printed line maps back to its originating operation.

Statements that matter

except ValueError as exc:
    print("int('²') raises:", exc)

Interactive Tools for This Topic

FAQ

What does the package manager see?
An empty dependency file. The snippet imports nothing that needs fetching. Its state lives in module-level bindings: `candidates`, `decimal_only`.