資訊內(nèi)容
python如何判斷是否為數(shù)字字符串
python判斷是否為數(shù)字字符串的方法:1、通過創(chuàng)建自定義函數(shù)【is_number()】方法來判斷字符串是否為數(shù)字;2、可以使用內(nèi)嵌if語句來實(shí)現(xiàn)。OJX少兒編程網(wǎng)-https://www.pxcodes.com
OJX少兒編程網(wǎng)-https://www.pxcodes.com
本教程操作環(huán)境:windows7系統(tǒng)、python3.9版,DELL G3電腦。OJX少兒編程網(wǎng)-https://www.pxcodes.com
python判斷是否為數(shù)字字符串的方法:
OJX少兒編程網(wǎng)-https://www.pxcodes.com
1、通過創(chuàng)建自定義函數(shù) is_number() 方法來判斷字符串是否為數(shù)字:OJX少兒編程網(wǎng)-https://www.pxcodes.com
實(shí)例OJX少兒編程網(wǎng)-https://www.pxcodes.com
# -*- 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('?')) # False2、我們也可以使用內(nèi)嵌 if 語句來實(shí)現(xiàn):OJX少兒編程網(wǎng)-https://www.pxcodes.com
執(zhí)行以上代碼輸出結(jié)果為:OJX少兒編程網(wǎng)-https://www.pxcodes.com
False True True True True True True True False3、更多方法OJX少兒編程網(wǎng)-https://www.pxcodes.com
Python isdigit() 方法檢測(cè)字符串是否只由數(shù)字組成。OJX少兒編程網(wǎng)-https://www.pxcodes.com
Python isnumeric() 方法檢測(cè)字符串是否只由數(shù)字組成。這種方法是只針對(duì)unicode對(duì)象。OJX少兒編程網(wǎng)-https://www.pxcodes.com
相關(guān)免費(fèi)學(xué)習(xí)推薦:python視頻教程OJX少兒編程網(wǎng)-https://www.pxcodes.com
以上就是python如何判斷是否為數(shù)字字符串的詳細(xì)內(nèi)容,更多請(qǐng)關(guān)注少兒編程網(wǎng)其它相關(guān)文章!OJX少兒編程網(wǎng)-https://www.pxcodes.com

- 上一篇
python int()怎么用
簡(jiǎn)介pythonint函數(shù)用于將一個(gè)字符串或數(shù)字轉(zhuǎn)換為整型,該函數(shù)的使用語法是“classint(x,base=10)”,其中參數(shù)x表示字符串或數(shù)字,參數(shù)base表示進(jìn)制數(shù),并且默認(rèn)十進(jìn)制。本教程操作環(huán)境:windows7系統(tǒng)、python3.5版,DELLG3電腦。int()函數(shù)用于將一個(gè)字符串或數(shù)字
- 下一篇
python如何重命名文件
簡(jiǎn)介python重命名文件的方法:首先打開pycharm,找到要重命名的文件;然后依次選擇【Refactor-Rename】,在重命名窗口輸入新的名稱;最后點(diǎn)擊【Refactor】按鈕即可。本教程操作環(huán)境:windows7系統(tǒng)、python3.9版,DELLG3電腦。python重命名文件的方法:1、打