Python 检查变量是否为整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3501382/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Checking whether a variable is an integer or not
提问by Hulk
How do I check whether a variable is an integer?
如何检查变量是否为整数?
采纳答案by Katriel
If you need to do this, do
如果您需要这样做,请执行
isinstance(<var>, int)
unless you are in Python 2.x in which case you want
除非你在 Python 2.x 中,在这种情况下你想要
isinstance(<var>, (int, long))
Do not use type. It is almost never the right answer in Python, since it blocks all the flexibility of polymorphism. For instance, if you subclass int, your new class should register as an int, which typewill not do:
不要使用type. 它在 Python 中几乎从来都不是正确的答案,因为它阻碍了多态性的所有灵活性。例如,如果你是 subclass int,你的新类应该注册为int,这type不会:
class Spam(int): pass
x = Spam(0)
type(x) == int # False
isinstance(x, int) # True
This adheres to Python's strong polymorphism: you should allow any object that behaves like an int, instead of mandating that it be one.
这符合 Python 强大的多态性:您应该允许任何行为类似于 的对象int,而不是强制它是一个。
BUT
但
The classical Python mentality, though, is that it's easier to ask forgiveness than permission. In other words, don't check whether xis an integer; assume that it is and catch the exception results if it isn't:
然而,经典的 Python 心态是请求宽恕比许可更容易。换句话说,不检查是否x是整数;假设它是,如果不是,则捕获异常结果:
try:
x += 1
except TypeError:
...
This mentality is slowly being overtaken by the use of abstract base classes, which let you register exactly what properties your object should have (adding? multiplying? doubling?) by making it inherit from a specially-constructed class. That would be the best solution, since it will permit exactlythose objects with the necessary and sufficient attributes, but you will have to read the docs on how to use it.
这种心态正慢慢被抽象基类的使用所取代,它让您可以通过从特殊构造的类继承来准确注册您的对象应该具有的属性(加法?乘法?加倍?)。这将是最好的解决办法,因为这将允许确切必要的和足够的属性的对象,但你必须阅读有关如何使用它的文档。
回答by Jungle Hunter
Found a related questionhere on SO itself.
在这里找到了一个关于 SO 本身的相关问题。
Python developers prefer to not check types but do a type specific operation and catch a TypeErrorexception. But if you don't know the type then you have the following.
Python 开发人员更喜欢不检查类型,而是执行特定于类型的操作并捕获TypeError异常。但如果你不知道类型,那么你有以下内容。
>>> i = 12345
>>> type(i)
<type 'int'>
>>> type(i) is int
True
回答by Matt Joiner
>>> isinstance(3, int)
True
See herefor more.
请参阅此处了解更多信息。
Note that this does not help if you're looking for int-like attributes. In this case you may also want to check for long:
请注意,如果您正在寻找int-like 属性,这无济于事。在这种情况下,您可能还想检查long:
>>> isinstance(3L, (long, int))
True
I've seen checks of this kind against an array/index type in the Python source, but I don't think that's visible outside of C.
我在 Python 源代码中看到过针对数组/索引类型的此类检查,但我认为这在 C 之外是不可见的。
Token SO reply:Are you sure you should be checking its type? Either don't pass a type you can't handle, or don't try to outsmart your potential code reusers, they may have a good reason not to pass an int to your function.
Token SO 回复:你确定你应该检查它的类型吗?要么不要传递您无法处理的类型,要么不要试图超越潜在的代码重用者,他们可能有充分的理由不将 int 传递给您的函数。
回答by S.Lott
Never. Check. Types.
绝不。查看。类型。
Do this. Always.
做这个。总是。
try:
some operation that "requires" an integer
except TypeError, e:
it wasn't an integer, fail.
回答by Scott Griffiths
If you reallyneed to check then it's better to use abstract base classesrather than concrete classes. For an integer that would mean:
如果您确实需要检查,那么最好使用抽象基类而不是具体类。对于一个整数,这意味着:
>>> import numbers
>>> isinstance(3, numbers.Integral)
True
This doesn't restrict the check to just int, or just intand long, but also allows other user-defined types that behave as integers to work.
这并不将检查限制为 justint或 just intand long,而且还允许行为为整数的其他用户定义类型工作。
回答by saroele
All proposed answers so far seem to miss the fact that a double (floats in python are actually doubles) can also be an integer (if it has nothing after the decimal point). I use the built-in is_integer()method on doubles to check this.
到目前为止,所有建议的答案似乎都忽略了一个事实,即双精度(python 中的浮点数实际上是双精度数)也可以是整数(如果小数点后没有任何内容)。我使用is_integer()双打的内置方法来检查这一点。
Example (to do something every xth time in a for loop):
示例(在 for 循环中每 x 次做某事):
for index in range(y):
# do something
if (index/x.).is_integer():
# do something special
Edit:
编辑:
You can always convert to a float before calling this method. The three possibilities:
在调用此方法之前,您始终可以转换为浮点数。三种可能:
>>> float(5).is_integer()
True
>>> float(5.1).is_integer()
False
>>> float(5.0).is_integer()
True
Otherwise, you could check if it is an int first like Agostino said:
否则,您可以像 Agostino 所说的那样首先检查它是否是 int :
def is_int(val):
if type(val) == int:
return True
else:
if val.is_integer():
return True
else:
return False
回答by Ramon Suarez
If the variable is entered like a string (e.g. '2010'):
如果变量像字符串一样输入(例如'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.
Before using this I worked it out with try/exceptand checking for (int(variable)), but it was longer code. I wonder if there's any difference in use of resources or speed.
在使用它之前,我使用try/except并检查了(int(variable))它,但它是更长的代码。我想知道在使用资源或速度方面是否有任何差异。
回答by NotNamedDwayne
why not just check if the value you want to check is equal to itself cast as an integer as shown below?
为什么不直接检查您要检查的值是否等于自身转换为整数,如下所示?
def isInt(val):
return val == int(val)
回答by sudokode
If you want to check that a string consists of only digits, but converting to an int won't help, you can always just use regex.
如果您想检查字符串是否仅由数字组成,但转换为 int 无济于事,您始终可以使用正则表达式。
import re
x = "01234"
match = re.search("^\d+$", x)
try: x = match.group(0)
except AttributeError: print("not a valid number")
Result: x == "01234"
In this case, if x were "hello", converting it to a numeric type would throw a ValueError, but data would also be lost in the process. Using a regex and catching an AttributeError would allow you to confirm numeric characters in a string with, for instance, leading 0's.
在这种情况下,如果 x 是“hello”,将其转换为数字类型会抛出 ValueError,但数据也会在此过程中丢失。使用正则表达式并捕获 AttributeError 将允许您确认字符串中的数字字符,例如,前导 0。
If you didn't want it to throw an AttributeError, but instead just wanted to look for more specific problems, you could vary the regex and just check the match:
如果您不希望它抛出 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"
That actually shows you where the problem occurred without the use of exceptions. Again, this is not for testing the type, but rather the characters themselves. This gives you much more flexibility than simply checking for types, especially when converting between types can lose important string data, like leading 0's.
这实际上向您展示了在不使用异常的情况下问题发生的位置。同样,这不是为了测试类型,而是为了测试字符本身。这比简单地检查类型为您提供了更大的灵活性,尤其是在类型之间转换可能会丢失重要的字符串数据时,例如前导 0。
回答by the noob
use the int function to help
使用 int 函数来帮助
intchecker = float(input('Please enter a integer: '))
intcheck = 0
while intcheck != 1:
if intchecker - int(intchecker) > 0:
intchecker = float(input("You didn't enter a integer. "
"Please enter a integer: "))
else:
intcheck = 1
print('you have entered a integer')

