liveBook · Manning

Str.isdigit

As explained in Python Workout, Second Edition

str.isdigit is a Python string method that returns whether all characters in a string are decimal digits and the string is nonempty.

Use str.isdigit() when a program needs to check whether a nonempty string contains only the digits 0–9 before converting it with int(). It returns True or False. section 5.9 section 8.7

Work through these boundaries before choosing it:

  • Accepts strings such as "42", but rejects empty strings, floating-point text such as "3.5", and negative text such as "-3". section 5.9 section 8.7
  • Filters list-comprehension input before int() runs, preventing conversion errors for entries such as "abcd". section 8.7
  • Prefer try/except ValueError when valid integers may include negative values; isdigit checks characters, not general convertibility. section 8.7
  • Distinguishes among isdigit, isdecimal, and isnumeric when their similar behavior matters. section 5.9

Validate before conversion

s = input('Enter a number: ').strip()\n\nif s.isdigit():\n n = int(s)\n print(f'You entered {n}. 2*{n} = {2*n}.')\nelse:\n print(f'{s} is not numeric.')

s = input('Enter a number: ').strip()

try:
    n = int(s)  #1
    print(f'You entered {n}. 2*{n} = {2*n}.')  #2
except ValueError:
    print(f'{s} is not numeric.')  #3

Compare character-based validation with try/except conversion, which also handles negative integers. section 8.7

How Python Workout, Second Edition covers it

How deep it goes
Explains the boolean check, conversion workflow, edge cases, and exception-based alternative, but stops short of general numeric parsing.
Examples
Demonstrates rainfall input, interactive number validation, and comprehension filtering.
What it assumes
Assumes familiarity with strings, method calls, int(), input(), and basic exception handling.
What you can do after
Apply it to reject non-digit input before int(), while diagnosing when try/except is the more suitable validation strategy.
How it connects
Connects string validation with int(), ValueError handling, list comprehensions, and related numeric string methods.

Also explained in

Compare how 2 books explain str.isdigit →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout, Second Edition. The section links point to the parts of the book it draws on.