Python isnumeric() function checks whether all the characters of the string are numeric characters or not. The isnumeric() function returns True if all the characters are true, otherwise returns False.
Python String isnumeric()
Python string isnumeric() is a built-in method that is used to check if the given string all the characters as numerals. The isnumeric() function returns True if all the characters present in the string are numeric and false in all other cases.
Numeric characters can be of different types such as integers, decimals, subscript, roman numerals, currency numerators, superscript,s, and many more. The main thing about numeric characters is that they all are present in Unicode.
Numeric characters include digit characters and all the characters which have the Unicode numeric value property.
We can define the method as isnumeric() only on the objects of Unicode objects. One more advantage of the isnumeric() method is that we can count the number of numeric values and use that in our solution generally used in competitive programming.
Syntax
string.isnumeric()
Here the string is the string that is to be checked if it is numeric or not.
Parameters
The method isnumeric() doesn’t contain any parameters.
Return Value
Python isnumeric() method returns true if the given string has its all characters as numerals and false if the string contains more than 1 non-numeric character.
Example programs on isnumeric() method:
Example 1: Write a program to show the demonstration of the isnumeric() method.
# app.py h1 = "12345678" h2 = "abc123def" h3 = "\u00BD" print("String: ", h1, " Numeric: ", h1.isnumeric()) print("String: ", h2, " Numeric: ", h2.isnumeric()) print("String: ", h3, " Numeric: ", h3.isnumeric())
Output
python3 app.py String: 12345678 Numeric: True String: abc123def Numeric: False String: ½ Numeric: True
Example 2: Write a program to check whether the two strings are numeric if yes print “Hello we are numeric” and print “Sorry we are not numeric” if they are not.
# app.py h1 = "Hello" h2 = "123" if(h1.isnumeric() and h2.isnumeric()): print("Hello we are numeric") else: print("Sorry we are not numeric")
Output
python3 app.py Sorry we are not numeric
That’s it for this tutorial.