如何检查变量是否为整数?
当前回答
一种更通用的方法将尝试检查整数和作为字符串给出的整数
def isInt(anyNumberOrString):
try:
int(anyNumberOrString) #to check float and int use "float(anyNumberOrString)"
return True
except ValueError :
return False
isInt("A") #False
isInt("5") #True
isInt(8) #True
isInt("5.88") #False *see comment above on how to make this True
其他回答
#######################################
# Value_Is_Int
#######################################
def value_is_int(value):
try:
tempVal = int(value)
return True
except:
return False
调用这个函数:
if value_is_int(value):
print "Integer"
else:
print "Not integer"
从来没有。检查。类型。
这样做。总是这样。
try:
some operation that "requires" an integer
except TypeError, e:
it wasn't an integer, fail.
这里有一个简单的例子,你可以确定一个整数
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
下面是这里提到的不同方法的总结:
Int (x) == x 尝试x = operator.index(x) isinstance (x, int) isinstance (x, numbers.Integral)
下面是它们如何应用于各种具有整数值的数值类型:
你可以看到它们不是100%一致的。Fraction和Rational在概念上是相同的,但是一个提供了.index()方法,而另一个没有。复杂类型不喜欢转换为int,即使实部是整数,虚部是0。
(np.int8|16|32|64(5)表示np.int8(5), np.int32(5)等行为相同)
在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")
推荐文章
- Django:“projects”vs“apps”
- 如何列出导入的模块?
- 转换Python程序到C/ c++代码?
- 如何从gmtime()的时间+日期输出中获得自epoch以来的秒数?
- 在python模块文档字符串中放入什么?
- 我如何在Django中过滤一个DateTimeField的日期?
- 在Python中用索引迭代列表
- -e,——editable选项在pip install中什么时候有用?
- 使用pip命令从requirements.txt升级python包
- Django更改默认的runserver端口
- 输入对象的datetime。Datetime没有Datetime属性
- numpy数组的Python内存使用情况
- NumPy或Pandas:保持数组类型为整数,同时具有NaN值
- 列表理解条件中的' elif '
- Python的“property”和“attribute”有什么区别?