Check If a Value is a Number Not a String in Python
To check a value is a number data type in Python and not a string, we can use the Python type()
function with some logic.
The three main number data types to evaluate are int
float
and decimal
:
import decimal
print(type(decimal.Decimal(4)))
print(type(int(4)))
print(type(float(4)))
<class 'decimal.Decimal'>
<class 'int'>
<class 'float'>
Now we can create some logic to check if the value is equal to the type, decimal.Decimal
, int or float like this:
num = '4'
if type(num) == decimal.Decimal or type(num) == int or type(num) == float:
print('It is a number.')
else:
print('Is a string some other data type.')
Is a string some other data type.