-->the start

今天写作业的时候突然想到,一直使用isdigit()方法来处理用户的输入选择是不是数字,但是如果用户输入的是负数呢,会不会导致bug?

然后我就试了一下,居然不报错。。。然后我就纳闷了,赶紧试了一下:

关于负数的isdigit()判断

先来看看str类的.isdigit()方法的文档。

1 def isdigit(self): # real signature unknown; restored from __doc__
2     """
3         S.isdigit() -> bool
4         
5         Return True if all characters in S are digits
6         and there is at least one character in S, False otherwise.
7     """
8     return False

 很显然'-10'.isdigit()返回False是因为'-'不是一个digit。

然后我就想怎么才能让负数也正确的判断为整数呢,下面是从网上找到的答案,在这里记录下来。

1 num = '-10'
2 if (num.startswith('-') and num[1:] or num).isdigit():
3     print(num是整数)
4 else:
5     print(num不是整数)

正则表达式法:

1 num = '-10'
2 import re
3 if re.match(r'^-?(\.\d+|\d+(\.\d+)?)', num):
4     print(num是整数)
5 else:
6     print(num不是整数)

更Pythonic的方法:

1 num = '-10'
2 if num.lstrip('-').isdigit():
3     print(num是整数)
4 else:
5     print(num不是整数)

当我看到第三个方法的时候,真是感触颇多,受益匪浅。

<--the end

相关文章:

  • 2022-12-23
  • 2021-10-02
  • 2021-09-24
  • 2021-10-31
  • 2022-02-20
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-14
  • 2022-12-23
相关资源
相似解决方案