PythonString methods
str. isdigit()
Checks whether a string consists only of digits.
- Returns
TrueorFalse.- Changes the original
- No
Example
#Python
for value in ["2026", "-5", "3.5", "", "12a"]:
print(repr(value), value.isdigit())
print("Emma".isalpha(), "code123".isalnum())Resultsaved result, you can check it
'2026' True
'-5' False
'3.5' False
'' False
'12a' False
True True
Definition and usage
#The isdigit() method returns True if the string is not empty and every character in it is a digit. It is handy for quickly checking whether text typed by a user can be converted to an integer.
It does not allow a minus sign, a period, or a space, so "-5" and "3.5" return False. For full number validation, it is more reliable to try the conversion inside a try block with int() or float().
Similar methods are isalpha() (letters only), isalnum() (letters and digits), and isspace() (whitespace only).
Syntax
#Syntax
string.isdigit()Good practices
#- To validate negative numbers and fractions, use
try: float(value). - An empty string always returns
Falseforis...()methods.
Related entries
#Spotted a mistake or missing an example? Write to us.