In a function in Django, the user can send me a number or a string, and I want to know if I received a number or a String (Tip: The number will always be an integer between 1-6)
I want to know if it's possible to detect this and how (with an example), as the number or string I'm getting will tell me what to do next.
To check if a variable is a Number in Python, use the type() function and compare its result with either int or float types to get the boolean value. If it returns True, then it is a Number. Otherwise, it is not a Number. The type() is a built-in Python function that returns the type of the argument we pass to it.
The standard solution to check if a given variable is an integer or not is using the isinstance() function. It returns True if the first argument is an instance of the second argument.
The most simple way (which works in Python 2.7. 11) is int(var) == var. Works with . 0 floats, returns boolean.
You can try to convert the string to a number using int()
, catching the exception:
def isNum(data):
try:
int(data)
return True
except ValueError:
return False
This returns True
only if the string can be converted to an integer number.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With