?
本文檔使用 php中文網(wǎng)手冊(cè) 發(fā)布
以下實(shí)例通過創(chuàng)建自定義函數(shù) is_number() 方法來判斷字符串是否為數(shù)字:
#?-*-?coding:?UTF-8?-*- #?Filename?:test.py #?author?by?:?www.shouce.ren def?is_number(s): ????try: ????????float(s) ????????return?True ????except?ValueError: ????????pass ????try: ????????import?unicodedata ????????unicodedata.numeric(s) ????????return?True ????except?(TypeError,?ValueError): ????????pass ????return?False #?測(cè)試字符串和數(shù)字 print(is_number('foo'))???#?False print(is_number('1'))?????#?True print(is_number('1.3'))???#?True print(is_number('-1.37'))?#?True print(is_number('1e3'))???#?True #?測(cè)試?Unicode #?阿拉伯語(yǔ)?5 print(is_number('?'))??#?False #?泰語(yǔ)?2 print(is_number('?'))??#?False #?中文數(shù)字 print(is_number('四'))?#?False #?版權(quán)號(hào) print(is_number('?'))??#?False
我們也可以使用內(nèi)嵌 if 語(yǔ)句來實(shí)現(xiàn):
執(zhí)行以上代碼輸出結(jié)果為:
False True True True True False False False False
Python isdigit() 方法檢測(cè)字符串是否只由數(shù)字組成。
Python isnumeric() 方法檢測(cè)字符串是否只由數(shù)字組成。這種方法是只針對(duì)unicode對(duì)象。