How to Check if a String is Numeric in Python?


Python - Check if a String is Numeric

To check if given string is numeric in Python, call isnumeric() function on this string.

The function returns True if the string contains only numeric characters and False if not.

The following are allowed characters for a string to be numeric.

0123456789

Examples

1. Check if given string '123456' is numeric

In this example, we take a String '123654' with only numeric characters. We will call isnumeric() function on this string to check if this string is numeric.

Python Program

x = '123654'
if x.isnumeric():
	print('x is numeric.')
else:
	print('x is not numeric.')

Output

x is numeric.

The function returns boolean value True, since the data in the string is numeric only.

2. Check if given string 'a123456' is numeric

In this example, we take a String 'a123654' with numeric characters and an alphabet. We will call isnumeric() function on this string to check if this string is numeric. The function should return False.

Python Program

x = 'a123654'
if x.isnumeric():
	print('x is numeric.')
else:
	print('x is not numeric.')

Output

x is not numeric.

The function returns boolean value True, since the data in the string is numeric only.

Summary

In summary, to determine if a given string is only numeric, use String.isnumeric() function.