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


当前回答

你也可以使用str.isdigit。尝试查找帮助(str.isdigit)

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

其他回答

如果你没有int,你可以这样做:

var = 15.4
if(var - int(var) != 0):
    print "Value is not integer"

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

例如:

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

如果你想写一个Python 2-3兼容的代码

要测试一个值是否为整数(任何类型),你可以这样做:

# Python 2 and 3: 
import sys
if sys.version_info < (3,):
    integer_types = (int, long,)
else:
    integer_types = (int,)

>>> isinstance(1, integer_types)
True

# Python 2 only:
if isinstance(x, (int, long)):
     ...

# Python 3 only:
if isinstance(x, int):
    ...

来源:http://python3porting.com/differences.html

如果变量像字符串一样输入(例如。“2010”):

if variable and variable.isdigit():
    return variable #or whatever you want to do with it. 
else: 
    return "Error" #or whatever you want to do with it.

在使用这个之前,我用try/except和检查(int(变量))解决了它,但它是较长的代码。我想知道在资源的使用和速度上是否有什么不同。

在python中检查是非常简单的。你可以这样做:

假设你想检查一个变量是否是整数!

## For checking a variable is integer or not in python

if type(variable) is int:
     print("This line will be executed")
else:
     print("Not an integer")