Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django, Detecting if variable is a number

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.

like image 629
Sascuash Avatar asked Nov 15 '13 14:11

Sascuash


People also ask

How do you check if a variable is a number in Python?

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.

How do you check if a variable is an integer?

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.

How do you check if a variable is an integer or a string in Python?

The most simple way (which works in Python 2.7. 11) is int(var) == var. Works with . 0 floats, returns boolean.


1 Answers

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.

like image 154
Martijn Pieters Avatar answered Sep 27 '22 21:09

Martijn Pieters