The isdecimal() method is a built-in method in Python programming language for string handling.
This method checks whether the string contains only decimal characters (0-9). This means that it will return True if all characters in the string are decimals (i.e., from 0 to 9), otherwise it will return False.
Syntax:
str.isdecimal()
How to use the isdecimal() method:
s = "123456"
print(s.isdecimal()) # This will output: True
s = "123456a"
print(s.isdecimal()) # This will output: False
s = "123.456"
print(s.isdecimal()) # This will output: False, because '.' is not a decimal character
Example 1
Validating User Input for Age.
age = input("Please enter your age: ")
if age.isdecimal():
print("Thank you!")
else:
print("Invalid input. Please enter a valid age.")
Example 2
Validating a Zip/Postal Code.
def is_valid_zip(zip_code):
if zip_code.isdecimal() and len(zip_code) == 5: # For a US ZIP code
return True
else:
return False
print(is_valid_zip("12345")) # Outputs: True
print(is_valid_zip("12345abc")) # Outputs: False