Checking whether a variable is an integer or not

Viewed 1759549

How do I check whether a variable is an integer?

41 Answers

You can also use str.isdigit. Try looking up help(str.isdigit)

def is_digit(str):
      return str.isdigit()

Here is a simple example how you can determine an integer

def is_int(x):
    print round(x),
    if x == round(x):
        print 'True',
    else:
        print 'False'

is_int(7.0)   # True
is_int(7.5)   # False
is_int(-1)    # True    
val=3
>>> isinstance(val,int ) 
True

will work.

Testing, if object is a string (works with Python 2.* and Python 3.* )

text = get_text()

try:
    text = text+""
except:
    return "Not a string"

do_something(text)

The simplest way is:

if n==int(n):
    --do something--    

Where n is the variable

Related