新聞中心
這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷解決方案
創(chuàng)新互聯(lián)Python教程:python判斷字符串是否為數(shù)字
以下實(shí)例通過創(chuàng)建自定義函數(shù) is_number() 方法來判斷字符串是否為數(shù)字:

更多相關(guān)內(nèi)容,請(qǐng)參考這篇文章:《python判斷字符是否為字母和數(shù)字》
# -*- coding: UTF-8 -*-
# Filename : test.py
# author by : www.runoob.com
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
# 阿拉伯語 5
print(is_number('?')) # True
# 泰語 2
print(is_number('?')) # True
# 中文數(shù)字
print(is_number('四')) # True
# 版權(quán)號(hào)
print(is_number('?')) # False我們也可以使用內(nèi)嵌 if 語句來實(shí)現(xiàn):
執(zhí)行以上代碼輸出結(jié)果為:
False True True True True True True True False
Python isdigit() 方法檢測(cè)字符串是否只由數(shù)字組成。
Python isnumeric() 方法檢測(cè)字符串是否只由數(shù)字組成。這種方法是只針對(duì)unicode對(duì)象。
網(wǎng)站名稱:創(chuàng)新互聯(lián)Python教程:python判斷字符串是否為數(shù)字
文章網(wǎng)址:http://m.fisionsoft.com.cn/article/cdgcghj.html


咨詢
建站咨詢
