如何检查变量是否为整数?
当前回答
你也可以使用str.isdigit。尝试查找帮助(str.isdigit)
def is_digit(str):
return str.isdigit()
其他回答
你可以这样做:
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'
同样的事情会发生
还有另一个选项可以进行类型检查。
例如:
n = 14
if type(n)==int:
return "this is an int"
import numpy as np
if (np.floor(x)-x == 0):
return "this is an int"
#######################################
# 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"
我可以检查数字是否是整数,包括像7.0这样的数字
def is_int(x):
if x - round(x) == 0 :
return True
else:
return False
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录