Python String isnumeric()
Python String isnumeric() method
Python String isnumeric() method is used to check if all characters in the string are numeric characters and there is at least one character in the string.
What are numeric characters? The characters whose Numeric_Type is Digit, Decimal, or Numeric.
Consider that given string is in x.
x = "123456"
Then the return value of x.isnumeric() is
True
In this tutorial, you will learn the syntax and usage of String isnumeric() method in Python language.
Syntax of isnumeric() method
The syntax of String isnumeric() method in Python is given below.
str.isnumeric()
Parameters
The isnumeric() method takes no parameters.
Return value
isnumeric() method returns a boolean value of True if all characters in the string are numeric characters and there is at least one character in the string, otherwise False.
Examples
1. Checking if given string is numeric in Python
In this example, we take a string value in variable x. We have to check if all characters in the string are numeric.
Call isnumeric() method on the string object x and use the returned value as a condition in Python if else statement as shown in the following program.
Since all characters in the string are digits (numeric), isnumeric() method returns True, and the if-block executes.
Python Program
x = "123456"
if x.isnumeric():
print('Given string is NUMERIC.')
else:
print('Given string is NOT NUMERIC.')
Output
Given string is NUMERIC.
2. Checking if given string (with some alphabets) is numeric in Python
In the following program, we take a string value in variable x such that some of the characters in the string are alphabets(non-numeric).
Since, not all characters in the string are numeric, isnumeric() method returns False, and the else-block executes.
Python Program
x = "123456abc"
if x.isnumeric():
print('Given string is NUMERIC.')
else:
print('Given string is NOT NUMERIC.')
Output
Given string is NOT NUMERIC.
3. Checking if an empty string is numeric in Python
In the following program, we take an empty string value in variable x, and check if this empty string is numeric.
Since, there is not at least one character in the string, isnumeric() method returns False, and the else-block executes.
Python Program
x = ""
if x.isnumeric():
print('Given string is NUMERIC.')
else:
print('Given string is NOT NUMERIC.')
Output
Given string is NOT NUMERIC.
Summary
In this tutorial of Python String Methods, we learned about String isnumeric() method, its syntax, and examples.