PythonPython StringsPython digit validation
How do you check whether a string contains only digits?
Question 74 of 88 · Updated
On this page
- 1. Check a string with isdigit()
- 2. Unicode decimal digits, digits and numeric characters
- 3. Require ASCII digits explicitly
- 4. Digit checks versus integer parsing
- 5. Practical example: validate a six-digit ASCII code
- 6. Convert accepted Unicode decimal digits into ASCII text
- 7. Bytes and explicit character iteration
- 8. Choose validation according to the requirement
- 9. Complexity and testing
- Common mistakes
- Interview-ready answer
- Official references
Use text.isdigit() to check whether a nonempty Python string consists entirely of Unicode digit characters. The method returns a Boolean. For decimal digits that can represent ordinary base-10 integer digits, use isdecimal(). For ASCII-only digit validation, combine isascii() with isdigit().
Choosing the right predicate matters: Unicode contains numeric characters that are not decimal digits, and a valid numeric literal can contain characters other than digits.
1. Check a string with isdigit()#
PYTHONfor text in ['123', '12a', '', '-12', '12.5', ' 12 ']: print(repr(text), text.isdigit())
Output:
'123' True
'12a' False
'' False
'-12' False
'12.5' False
' 12 ' FalseThe method returns True only if the input contains at least one character and every character qualifies as a Unicode digit. Empty strings return False.
A minus sign, decimal point, surrounding whitespace or alphabetic character prevents the predicate from succeeding. This is intentional: isdigit checks a character-class requirement, not whether the string can be interpreted as a number.
The method returns a bool, does not parse an integer, and does not modify the original string.
2. Unicode decimal digits, digits and numeric characters#
Python provides three related predicates, whose accepted Unicode character classes form a hierarchy.
PYTHONfor text in ['123', '١٢٣', '²', '½', '四', '']: print(repr(text), text.isdecimal(), text.isdigit(), text.isnumeric())
Output:
'123' True True True
'١٢٣' True True True
'²' False True True
'½' False False True
'四' False False True
'' False False False| Predicate | Unicode classification | Example accepted |
|---|---|---|
| isdecimal() | Decimal digits, Numeric_Type=Decimal | Arabic-Indic digit ٣ |
| isdigit() | Numeric_Type=Decimal or Digit | Superscript ² |
| isnumeric() | Numeric_Type=Decimal, Digit or Numeric | Vulgar fraction ½ |
The Chinese character 四, meaning four, has a Unicode numeric value and is accepted by isnumeric(), despite not being a decimal digit. All three predicates reject empty strings.
Every nonempty string that passes isdecimal also passes isdigit and isnumeric. Every string that passes isdigit passes isnumeric. The reverse implications do not hold.
The classifications are defined by Unicode properties, not just appearance. Python's Unicode database version can affect the treatment of characters introduced or reclassified in later Unicode versions.
3. Require ASCII digits explicitly#
When a protocol or identifier requires only the ten characters 0 through 9, Unicode digit acceptance is too broad.
A concise check is:
text.isascii() and text.isdigit()
The isascii method alone accepts every ASCII character, including letters and punctuation, and accepts an empty string. The isdigit condition supplies the nonempty digit requirement.
A regular expression provides another way to express the accepted alphabet.
PYTHONimport re for text in ['123', '١٢٣', '²', '123\n', '']: print(repr(text), bool(re.fullmatch(r'[0-9]+', text)), bool(re.fullmatch(r'\d+', text)))
Output:
'123' True True
'١٢٣' False True
'²' False False
'123\n' False False
'' False FalseIn Python's default Unicode regular-expression mode for str patterns, the digit escape matches Unicode decimal digits, not all characters accepted by isdigit. The explicit character range [0-9] accepts only ASCII decimal digits. The re.ASCII flag can also restrict the digit escape to ASCII behavior.
Use fullmatch when validating the entire input, rather than searching for a digit anywhere or matching only an initial portion. The plus quantifier requires at least one matching character.
For simple ASCII digit validation, the two string predicates are usually easier to read than introducing a regex.
4. Digit checks versus integer parsing#
PYTHONprint(int('١٢٣'), int('123')) print(int(' -12 '), int('1_000')) try: int('²') except ValueError: print('not an integer literal')
Output:
123 123
-12 1000
not an integer literalThe int constructor accepts Unicode decimal digits when parsing ordinary base-10 strings. It can also accept a sign, surrounding whitespace and permitted underscore separators. Those additional characters cause the complete string to fail isdigit or isdecimal.
Conversely, superscript ² passes isdigit but does not represent a valid decimal integer literal for int.
Therefore, the questions "does this consist only of digits?" and "can this be parsed as an integer?" have different answers. If the requirement is integer conversion, attempt int using the intended base and handle ValueError at the input boundary. If the requirement is a particular accepted syntax, validate that syntax first.
Successful isdecimal classification means the characters are decimal digits, but does not guarantee that converting an arbitrarily long string will succeed. CPython can impose a configurable decimal integer conversion length limit; memory and other resource constraints also matter.
Avoid using float parsing as a digits-only validator. Floating-point syntax can include decimal points, signs, exponent notation and special values such as infinity and NaN. Floating-point conversion also has different precision and range behavior.
5. Practical example: validate a six-digit ASCII code#
PYTHONdef parse_pin(text): if not isinstance(text, str): raise TypeError('expected text') if len(text) != 6 or not (text.isascii() and text.isdigit()): raise ValueError('expected six ASCII digits') return text print(parse_pin('001234')) try: parse_pin('١٢٣٤٥٦') except ValueError as exc: print(exc)
Output:
001234
expected six ASCII digitsThis function implements a specific contract: an input must be a string containing exactly six ASCII digits. It deliberately rejects Unicode digits outside ASCII, extra whitespace and incorrect lengths. Returning a string preserves leading zeros.
This is format validation only. It does not authenticate a user, verify the code against an expected value, enforce expiration or protect against repeated guesses.
Identifiers such as postal codes, account reference strings and verification codes may have significant leading zeros. Converting them to int can destroy information that is part of the identifier. Store and compare them according to the relevant format specification.
Do not automatically strip whitespace or normalize arbitrary input unless the contract explicitly permits it. For sensitive codes, avoid recording raw values in application logs.
6. Convert accepted Unicode decimal digits into ASCII text#
Some applications intentionally accept decimal digits from several writing systems but use ASCII decimal characters as an internal text representation.
PYTHONfrom unicodedata import decimal def decimal_to_ascii(text): if not text.isdecimal(): raise ValueError('expected nonempty decimal digits') return ''.join(str(decimal(ch)) for ch in text) print(decimal_to_ascii('٠12')) print(decimal_to_ascii('007'))
Output:
012
007The helper first verifies that every character is a Unicode decimal digit. It then uses unicodedata.decimal to obtain each character's decimal value and formats that value as an ASCII digit.
Unlike converting the entire string to int and back to str, this preserves the number of digits and leading zeros. It also accepts mixed writing systems, as the first example demonstrates. A system that prohibits mixed-script input needs an additional policy.
This function assumes a str input. The accepted decimal-digit vocabulary and conversion behavior depend on the interpreter's Unicode database.
Do not substitute broad compatibility normalization without considering its effects. For example, NFKC can transform superscript digits or other compatibility characters into ordinary text, changing which original inputs are accepted. Decide whether validation is applied to the original or normalized representation.
7. Bytes and explicit character iteration#
PYTHONprint(b'123'.isdigit()) print('١٢٣'.isdigit()) print('١٢٣'.encode('utf-8').isdigit()) print(all('0' <= ch <= '9' for ch in ''))
Output:
True
True
False
TrueThe bytes.isdigit method tests nonempty sequences of ASCII digit bytes. It does not decode UTF-8 into Unicode code points, so encoded Arabic-Indic digits fail the binary predicate even though their decoded text passes str.isdigit.
For Unicode text, decode using the known encoding before applying Unicode classification. For binary protocols, use byte-oriented validation when the protocol defines ASCII bytes.
An explicit ASCII check can also be expressed as bool(text) and all('0' <= ch <= '9' for ch in text). The bool(text) condition is important because all over an empty iterable returns True. Without that condition, an empty string would incorrectly pass a nonempty digits-only requirement.
8. Choose validation according to the requirement#
| Requirement | Recommended approach |
|---|---|
| Nonempty Unicode digit string | isdigit() |
| Nonempty Unicode decimal-digit string | isdecimal() |
| Nonempty string of Unicode numeric characters | isnumeric() |
| Nonempty ASCII digit string | isascii() and isdigit() |
| Fixed-length ASCII identifier | Length check plus ASCII digit validation |
| Signed integer conversion | int() with appropriate error and size handling |
| Decimal or floating-point number | Defined numeric grammar and appropriate parser |
The distinction is about the domain's accepted syntax and semantics. A human-facing number field, an ASCII network protocol and an account identifier can all have different requirements.
The isnumeric method does not mean that int or float can parse every accepted input, and it does not establish that the entire string represents one meaningful number. A string of individually numeric characters may not be a valid number in the intended format.
9. Complexity and testing#
For an ordinary string of length n, the classification predicates examine code points until a disallowed character is encountered or the end is reached. Their usual worst-case time complexity is O(n), with constant auxiliary storage under a fixed Unicode database and ordinary CPython implementation model. Early termination can reduce the actual work.
An explicit ASCII character loop has a similar worst-case traversal cost. CPython can use internal representation information to answer isascii efficiently; this is an implementation detail rather than a universal language-level complexity guarantee.
The decimal_to_ascii helper processes each accepted character and constructs a complete output string. Its typical time and output storage are O(n), with possible temporary storage for the generated fragments. For externally supplied text, bound input length before expensive parsing or conversion.
A good validation suite includes ASCII digits, non-ASCII decimal digits, superscripts, fractions, uncased numeric ideographs, mixed digit scripts, empty input, whitespace, signed values, decimal points and incorrect lengths.
Common mistakes#
- Assuming isdigit accepts only ASCII characters.
- Assuming a string that passes isdigit can always be converted with int.
- Treating an empty string as digits-only because all() returns True on empty input.
- Accepting a partial regex match when the entire string must be validated.
- Converting a digit identifier to an integer and losing leading zeros.
- Assuming Unicode normalization is harmless for every identifier or security-sensitive value.
Interview-ready answer#
Python's str.isdigit() returns True when a string is nonempty and all its characters are Unicode digits. The narrower str.isdecimal() accepts Unicode decimal digits, while str.isnumeric() also accepts other Unicode numeric characters such as fractions. For ASCII-only validation, use text.isascii() and text.isdigit(). These methods validate character classes rather than parsing numeric literals: a signed integer can fail isdigit, while a superscript digit can pass isdigit but fail int conversion. Select the predicate according to the actual input format, and preserve identifiers as strings when leading zeros matter.
Official references#
- Python Standard Library — str.isdigit
- Python Standard Library — str.isdecimal
- Python Standard Library — str.isnumeric
- Python Standard Library — str.isascii
- Python Standard Library — int
- Python Standard Library — Regular expression syntax
- Python Standard Library — unicodedata
- Python Standard Library — Integer string conversion length limitation
Verification note: Seven runnable example groups matched their documented outputs in independent namespaces on CPython 3.13.5 using Unicode database 15.1.0. Four expected exception tests passed. Across 500 seeded randomized strings, 2,000 assertions verified the three Unicode predicates against per-code-point unicodedata classifications and the ASCII predicate against an independent character-range check. Two fenced Mermaid diagrams were manually reviewed; the local Mermaid CLI was unavailable, so parser-level verification and public-site rendering were not performed. Official references are supplied under the authorized offline research exception; live documentation and Supabase changelog were not checked.
References
- 1.Python Standard Library — str.isdigitdocs.python.org
- 2.Python Standard Library — intdocs.python.org
- 3.Python Standard Library — Regular expression syntaxdocs.python.org
- 4.Python Standard Library — unicodedatadocs.python.org
Related questions
Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design