Python str.isdigit() function


In Python, the str.isdigit() method is used to check if all characters in a string are digits. This method returns True if all characters in the string are numeric characters (i.e., 0 through 9) and there is at least one character; otherwise, it returns False.

Syntax

str.isdigit()

Example Usage

  1. Basic usage with digits:
text = "12345" result = text.isdigit() print(result) # Output: True
  1. Including non-digit characters:
text = "123abc" result = text.isdigit() print(result) # Output: False
  1. Checking an empty string:
text = "" result = text.isdigit() print(result) # Output: False
  1. With spaces and punctuation:
text = "123 456" result = text.isdigit() print(result) # Output: False
  1. Using special numeric characters:

The isdigit() method also returns True for characters that are considered numeric in Unicode, such as fractions and superscripts:

text = "²³" result = text.isdigit() # Superscripts are considered digits print(result) # Output: True
  1. Negative numbers and decimals:
text = "-123" result = text.isdigit() # Negative sign is not a digit print(result) # Output: False text = "123.45" result = text.isdigit() # Decimal point is not a digit print(result) # Output: False

Important Notes

  • The isdigit() method considers characters that are numeric, including those in various scripts (like Arabic numerals) and even other characters defined as digits in Unicode.
  • It will return False for any string containing non-numeric characters, including letters, spaces, punctuation, and symbols.

Summary

  • Use str.isdigit() to determine if a string consists entirely of digit characters.
  • It returns True for strings made up only of digits (0-9) and False for any strings containing non-digit characters.