-->the startgit
今天写做业的时候忽然想到,一直使用isdigit()方法来处理用户的输入选择是否是数字,可是若是用户输入的是负数呢,会不会致使bug?正则表达式
而后我就试了一下,竟然不报错。。。而后我就纳闷了,赶忙试了一下:spa
先来看看str类的.isdigit()方法的文档。rest
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。code
而后我就想怎么才能让负数也正确的判断为整数呢,下面是从网上找到的答案,在这里记录下来。blog
1 num = '-10' 2 if (num.startswith('-') and num[1:] or num).isdigit(): 3 print(num是整数) 4 else: 5 print(num不是整数)
正则表达式法:ip
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不是整数)
当我看到第三个方法的时候,真是感触颇多,受益不浅。it
<--the endast