如何检查变量是否为整数?


当前回答

你可以这样做:

name = 'Bob'
if type(name) == str:
    print 'this works'
else:
    print 'this does not work'

它会返回'this works'…但是如果你将name改为int(1),那么它将返回'this does not work',因为它现在是一个字符串… 你也可以试试:

name = int(5)
if type(name) == int:
    print 'this works'
else:
    print 'this does not work'

同样的事情会发生

其他回答

你可以做到的。

if type(x) is int:

一个简单的方法是直接检查除以1的余数是否为0。

if this_variable % 1 == 0:
    list.append(this_variable)
else:
    print 'Not an Integer!'

还有另一个选项可以进行类型检查。

例如:

  n = 14
  if type(n)==int:
  return "this is an int"

最简单的方法是:

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

变量n在哪

#!/usr/bin/env python

import re

def is_int(x):

    if(isinstance(x,(int,long))):

        return True
    matchObj = re.match(r'^-?\d+\.(\d+)',str(x))

        if matchObj:

        x = matchObj.group(1)

        if int(x)-0==0:

            return True

     return False

print is_int(6)

print is_int(1.0)

print is_int(1.1)

print is_int(0.1)

print is_int(-956.0)