Django Detecting if a variable is a number

In a function in Django, a 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 from 1 to 6)

I want to know if this can be detected and how (with an example), since the number or string that I get will tell me what to do next.

+4
source share
3 answers

You can try to convert a string to a number with int(), catching the exception:

def isNum(data):
    try:
        int(data)
        return True
    except ValueError:
        return False

This returns Trueonly if the string can be converted to an integer.

+5
source

What about: if isinstance(data, int):

+2

, , .. "1" "4" "6" - , ; , , , , .

def isNumber(your_input_string):
    return len(your_input_string) == 1 and your_input_string in "123456"

1 6, 1 "123456", ... , .

Martijn Pieters , ; , "1" "6".

def isNumber(your_input_string):
    return len(your_input_string) == 1 and '1' <= your_input_string <= '6'
+1

All Articles