Python String isdigit() Method
The Python isdigit() method detects whether a string consists of only digits.
Python String isdigit() Syntax
isdigit() method syntax.
str.isdigit()
Python String isdigit() Parameters
- None.
Python String isdigit() Return Value
Returns True if the string contains only numbers, otherwise returns False.
Python String isdigit() Example#1
The following example shows an example of the isdigit() method.
#!/usr/bin/python3
str = "123456789";
print (str.isdigit())
str = "Apidemos example....wow!!!"
print (str.isdigit())
Output:
Python String isdigit() Example#2
isdigit() method is only valid for positive integers, negative numbers and decimals are returned incorrectly.
The following functions can be used to resolve this.
#! /usr/bin/python3
# Determine if it is a number
def is_number(s):
try: # Return True if the float(s) statement works (string s is a floating point number)
float(s)
return True
except ValueError: # ValueError is a standard Python exception that indicates "no valid argument was passed".
pass # If a ValueError exception is raised, do nothing (pass: do nothing, usually as a placeholder statement)
try:
import unicodedata # Packages that handle ASCII codes
unicodedata.numeric(s) # A function that converts a string that shows a number to a floating-point number to be returned
return True
except (TypeError, ValueError):
pass
return False
print(is_number(1))
print(is_number(1.0))
print(is_number(0))
print(is_number(-2))
print(is_number(-2.0))
print(is_number("abc"))
Output:
Python String isdigit() Example#3
A string containing numeric and numeric characters.
#!/usr/bin/python3
s = '12345'
print(s.isdigit())
# s = '²3456' subscript is a digit
s = '\u00B23455'
print(s.isdigit())
# s = '½' fraction is not a digit
s = '\u00BD'
print(s.isdigit())
Output: