在 Python 中實現 IsNumber() 函式


在本文中,我們將介紹使用 Python 3.x 或更早版本實現 isNumber() 方法。

此方法以字串型別作為輸入,並根據輸入字串是否為數字返回布林值 True 或 False。為此,我們藉助 try 和 except 語句使用了異常處理。

示例

我們看幾個示例 −

 即時演示

# Implementation of isNumber() function
def isNumber(s):
   if(s[0] =='-'):
      s=s[1:]
   #exception handling
   try:
      n = int(s)
      return True
   # catch exception if any error is encountered
   except ValueError:
      return False
inp1 = "786"
inp2 = "-786"
inp3 = "Tutorialspoint"
print(isNumber(inp1))
print(isNumber(inp2))
print(isNumber(inp3))

輸出

True
True
False

結論

在本文中,我們學習瞭如何在 Python 3.x 或更早版本中實現 Implement IsNumber() 函式。

更新於: 29-Aug-2019

105 次瀏覽

開啟你的 職業生涯

參加課程,取得認證

開始學習
廣告
© . All rights reserved.