Python 检查数字是否为整数
发布: (2026年2月24日 GMT+8 12:53)
2 分钟阅读
原文: Dev.to
Source: Dev.to
def is_int(x: int | float | str | None):
"""
Return True if *x* represents an integer value, otherwise False.
Handles:
- int, float, and numeric strings (e.g., "12", "12.0")
- None or non‑numeric strings gracefully return False
"""
try:
return float(x).is_integer()
except (TypeError, ValueError):
return False
工作原理
float(x)尝试将输入转换为浮点数。is_integer()检查得到的浮点数是否没有小数部分。- 如果转换失败(例如
x为None或非数字字符串),会捕获TypeError或ValueError,函数返回False。
示例用法(测试案例)
# 正面案例 – 应返回 True
a1 = 12.0
a2 = "12.0"
a3 = "012.0"
b1 = 12
b2 = "12"
b3 = "012"
# 负面案例 – 应返回 False
c1 = 12.34
c2 = "12.34"
c3 = "012.34"
d1 = None
d2 = "12X100ML"
d3 = "12.x"
print(is_int(a1)) # True
print(is_int(a2)) # True
print(is_int(a3)) # True
print(is_int(b1)) # True
print(is_int(b2)) # True
print(is_int(b3)) # True
print(is_int(c1)) # False
print(is_int(c2)) # False
print(is_int(c3)) # False
print(is_int(d1)) # False
print(is_int(d2)) # False
print(is_int(d3)) # False
为什么 isinstance(x, int) 不足以判断
- 字符串数字:
"12"或"12.0"并不是int实例。 - 数学上是整数的浮点数:
12.0是float,但表示整数值。 - 无效输入:像
"abc"或"12.x"这样的非数字字符串应返回False,且不抛出异常。
另一种(更冗长)实现方式
def is_int(x: int | float | str | None):
if isinstance(x, str):
try:
x = float(x)
except (TypeError, ValueError):
return False
if isinstance(x, int):
return True
if isinstance(x, float):
return x.is_integer()
return False
正则表达式方法
正则方案是可行的,但会增加不必要的复杂度。上面展示的内置转换方式简洁且可靠。(想了解正则实现,请参见我的另一篇文章。)