str爲字符串s爲字符串html
str.isalnum() 全部字符都是數字或者字母python
str.isalpha() 全部字符都是字母git
str.isdigit() 全部字符都是數字安全
str.isspace() 全部字符都是空白字符、t、n、rpost
檢查字符串是數字/浮點數方法spa
float部分code
>> float('Nan') nan >> float('Nan') nan >> float('nan') nan >> float('INF') inf >> float('inf') inf >> float('-INF') inf >> float('-inf') inf
第一種:最簡單htm
def is_number(str): try: # 由於使用float有一個例外是'NaN' if str=='NaN': return False float(str) return True except ValueError: return False
>>> float('NaN') nan
使用complex()unicode
def is_number(s): try: complex(s) # for int, long, float and complex except ValueError: return False return True
綜合1字符串
def is_number(s): try: float(s) # for int, long and float except ValueError: try: complex(s) # for complex except ValueError: return False return True
綜合2-仍是沒法徹底識別
def is_number(n): is_number = True try: num = float(n) # 檢查 "nan" is_number = num == num # 或者使用 `math.isnan(num)` except ValueError: is_number = False return is_number >>> is_number('Nan') False >>> is_number('nan') False >>> is_number('123') True >>> is_number('-123') True >>> is_number('-1.12') True >>> is_number('abc') False >>> is_number('inf') True
第二種:只能判斷是整數
使用isnumeric()
# str必須是uniconde模式 >>> str = u"345" >>> str.isnumeric()True http://www.tutorialspoint.com/python/string_isnumeric.htm
http://docs.python.org/2/howt...
使用isdigit()
https://docs.python.org/2/lib...
>>> str = "11" >>> print str.isdigit() True >>> str = "3.14" >>> print str.isdigit() False >>> str = "aaa" >>> print str.isdigit() False
使用int()
def is_int(str): try: int(str) return True except ValueError: return False
第三種:使用正則(最安全方法)
import re def is_number(num): pattern = re.compile(r'^[-+]?[-0-9]\d*\.\d*|[-+]?\.?[0-9]\d*$') result = pattern.match(num) if result: return True else: return False >>>: is_number('1') True >>>: is_number('111') True >>>: is_number('11.1') True >>>: is_number('-11.1') True >>>: is_number('inf') False >>>: is_number('-inf') False