少儿编程100讲轻松学python(四)-python如何判断是否为数字字符串
生活随笔
收集整理的這篇文章主要介紹了
少儿编程100讲轻松学python(四)-python如何判断是否为数字字符串
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
前言
python判斷是否為數字字符串的方法:
1、通過創建自定義函數【is_number()】方法來判斷字符串是否為數字;
2、可以使用內嵌if語句來實現。
python判斷是否為數字字符串的方法:
1、通過創建自定義函數 is_number() 方法來判斷字符串是否為數字:
實例
# -*- coding: UTF-8 -*-# Filename : test.py # author by : www.runoob.comdef is_number(s):try:float(s)return Trueexcept ValueError:passtry:import unicodedataunicodedata.numeric(s)return Trueexcept (TypeError, ValueError):passreturn False# 測試字符串和數字 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# 測試 Unicode # 阿拉伯語 5 print(is_number('?')) # True # 泰語 2 print(is_number('?')) # True # 中文數字 print(is_number('四')) # True # 版權號 print(is_number('?')) # False2、我們也可以使用內嵌 if 語句來實現:
執行以上代碼輸出結果為:
False True True True True True True True False3、更多方法
Python isdigit() 方法檢測字符串是否只由數字組成。
Python isnumeric() 方法檢測字符串是否只由數字組成。這種方法是只針對unicode對象。
總結
以上是生活随笔為你收集整理的少儿编程100讲轻松学python(四)-python如何判断是否为数字字符串的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 少儿编程100讲轻松学python(三)
- 下一篇: 少儿编程100讲轻松学python(六)