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


当前回答

我在所有软件中使用的一个简单方法是这样的。它检查变量是否由数字组成。

test = input("Enter some text here: ")
if test.isdigit() == True:
   print("This is a number.")
else:
   print("This is not a number.")

其他回答

如果你想检查一个字符串是否只由数字组成,但转换为int型没有帮助,你总是可以使用regex。

import re
x = "01234"
match = re.search("^\d+$", x)
try: x = match.group(0)
except AttributeError: print("not a valid number")

Result: x == "01234"

在这种情况下,如果x是"hello",将其转换为数值类型会抛出ValueError,但数据也会在此过程中丢失。使用正则表达式并捕获AttributeError将允许您确认字符串中的数字字符,例如,前导0。

如果你不想让它抛出AttributeError,而只是想寻找更具体的问题,你可以改变正则表达式,只检查匹配:

import re
x = "h01234"
match = re.search("\D", x)
if not match:
    print("x is a number")
else:
    print("encountered a problem at character:", match.group(0))

Result: "encountered a problem at character: h"

这实际上显示了问题发生的位置,而不使用异常。同样,这不是为了测试类型,而是测试字符本身。这比简单地检查类型要灵活得多,特别是当类型之间的转换可能会丢失重要的字符串数据时,比如前导0。

如果你想写一个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

测试,如果object是一个字符串(适用于Python 2。*和Python 3。*)

text = get_text()

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

do_something(text)

如果你真的需要检查,那么最好使用抽象基类而不是具体类。对于一个整数,这意味着:

>>> import numbers
>>> isinstance(3, numbers.Integral)
True

这并没有将检查限制为仅int或仅int和long,而是还允许其他用户定义的行为为整数的类型工作。

如果您正在从一个文件中读取数据,并且您有一个具有多种数据类型值的数组或字典,那么以下内容将很有用。 只需检查变量是否可以类型转换为int(或您想强制执行的任何其他数据类型)。

try :
    int(a);
    #Variable a is int
except ValueError : 
    # Variable a is not an int