-->the start
今天寫作業的時候突然想到,一直使用isdigit()方法來處理用戶的輸入選擇是不是數字,但是如果用戶輸入的是負數呢,會不會導致bug?
然后我就試了一下,居然不報錯。。。然后我就納悶了,趕緊試了一下:
先來看看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