【Python】str.isdigit() 和 float.is_integer()的用法和区别,判断数据是否是数字

str.isdigit() 和 float.is_integer()都可以判断数据是否是数字,但是二者是有一定区别的,具体见代码。

 

# str.isdigit(),用来判断1个字符串str是否全部都是数字,如果是,返回True
a = 5;      print(a.isdigit())     # AttributeError: 'int' object has no attribute 'isdigit'
e = -5;     print(e.isdigit())     # AttributeError: 'int' object has no attribute 'isdigit'
b = 5.5;    print(b.isdigit())     # AttributeError: 'float' object has no attribute 'isdigit'
f = -5.5;   print(f.isdigit())     # AttributeError: 'float' object has no attribute 'isdigit'
c = '5';    print(c.isdigit())     # True
d = '5.5';  print(d.isdigit())     # False
g = '-5';   print(g.isdigit())     # False
h = '-5.5'; print(h.isdigit())     # False

# ------------------------------------------------------------------------

# float.is_integer(),用来判断1个浮点数float是否是整数(小数点都是0),如果是,返回True(正负数均可)
a = 5;      print(a.is_integer())  # AttributeError: 'int' object has no attribute 'is_integer'
e = -5;     print(e.is_integer())  # AttributeError: 'int' object has no attribute 'is_integer'
c = '5';    print(c.is_integer())  # AttributeError: 'str' object has no attribute 'is_integer'
d = '5.5';  print(d.is_integer())  # AttributeError: 'str' object has no attribute 'is_integer'
g = '-5';   print(g.is_integer())  # AttributeError: 'str' object has no attribute 'is_integer'
h = '-5.5'; print(h.is_integer())  # AttributeError: 'str' object has no attribute 'is_integer'
i = -5.0;   print(i.is_integer())  # True
j = 5.0;    print(j.is_integer())  # True
b = 5.5;    print(b.is_integer())  # False
f = -5.5;   print(f.is_integer())  # False

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值