Python 判断字符串是否为数字


以下实例通过创建自定义函数 is_number() 方法来判断字符串是否为数字:

  1. # -*- coding: UTF-8 -*-
  2.  
  3. # Filename :test.py
  4. # author by : www.shouce.ren
  5.  
  6. def is_number(s):
  7.     try:
  8.         float(s)
  9.         return True
  10.     except ValueError:
  11.         pass
  12.  
  13.     try:
  14.         import unicodedata
  15.         unicodedata.numeric(s)
  16.         return True
  17.     except (TypeError, ValueError):
  18.         pass
  19.  
  20.     return False
  21.  
  22. # 测试字符串和数字
  23. print(is_number('foo'))   # False
  24. print(is_number('1'))     # True
  25. print(is_number('1.3'))   # True
  26. print(is_number('-1.37')) # True
  27. print(is_number('1e3'))   # True
  28.  
  29. # 测试 Unicode
  30. # 阿拉伯语 5
  31. print(is_number('٥'))  # False
  32. # 泰语 2
  33. print(is_number('๒'))  # False
  34. # 中文数字
  35. print(is_number('四')) # False
  36. # 版权号
  37. print(is_number('©'))  # False

我们也可以使用内嵌 if 语句来实现:

执行以上代码输出结果为:

  1. False
  2. True
  3. True
  4. True
  5. True
  6. False
  7. False
  8. False
  9. False

更多方法

Python isdigit() 方法检测字符串是否只由数字组成。

Python isnumeric() 方法检测字符串是否只由数字组成。这种方法是只针对unicode对象。