Python string isnumeric() method is used to check if all the characters in the string are numeric(digits). It returns True if all the characters in the string are numeric(digits) and false in all other cases.
Syntax
string.isnumeric()
Parameters
This method doesn’t contain any parameters. If you pass parameters then it returns an error.
Return Value
Returns true if the given string has all its characters as numerals and false if the string contains more than 1 non-numeric character.
Visual Representation
Example 1: How to Use String isnumeric() Method
string = "1234567"
string2 = "abc123def"
string3 = "¾"
print(string.isnumeric())
print(string2.isnumeric())
#Exponents(² and ¾) are also considered to be numeric values
print(string3.isnumeric())
Output
True
False
True
The third string (“¾”) contains Exponents(like ¾), so it returns True.
Example 2: Using conditional statement
string = "1234567"
string2 = "-1234567"
if(string.isnumeric()):
print("1234567 is numeric")
else:
print("1234567 is not numeric ")
if(string2.isnumeric()):
print("-1234567 is numeric")
else:
print("-1234567 is not numeric ")
Output
1234567 is numeric
-1234567 is not numeric
As you can see first string “1234567” is numeric, while the second string “-1234567” is not numeric because it contains a negative sign.
Example 3: White spaces are not considered to be numeric
string = ""
string2 = "123 4567"
print(string.isnumeric())
print(string2.isnumeric())
Output
False
False
Example 4: Errors and Exceptions
string = "12345"
print(string.isnumeric("67"))
Output
TypeError: str.isnumeric() takes no arguments (1 given)