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.
Code
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
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.ASCII Table ReferenceLook up any ASCII code point 0-127 by decimal, hex, or character and see the binary, octal, and control-name view.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.