方法簽名
str.isnumeric() -> bool
行為定義
回傳 True 當且僅當:
- 字串 非空;
- 字串中 每一個字元 皆為 Unicode 數字字元 (General Category = Nd, Nl, No)。
包含:阿拉伯數字 0-9、全形數字 0-9、羅馬數字 ⅰⅱⅲ、中文數字 一二三四五六七八九十百千萬億、其他語系數字字元。
不包含:負號、小數點、指數符號、空白、字母、中文數字單位 (十、百、千) 以外的漢字。
範例與邊界
>> '12345'.isnumeric()
True
>>> '0123'.isnumeric() # 全形數字
True
>>> 'Ⅷ'.isnumeric() # 羅馬數字
True
>>> '一二三'.isnumeric() # 中文數字
True
>>> '12.34'.isnumeric() # 含小數點
False
>>> '-123'.isnumeric() # 含負號
False
>>> '123abc'.isnumeric() # 含字母
False
>>> ''.isnumeric() # 空字串
False
>>> ' 123 '.isnumeric() # 含空白
False
>>> '¹²³'.isnumeric() # 上標數字 (No 類別)
True
與 isdigit()、isdecimal() 差異比較
| 字串 | isdecimal() | isdigit() | isnumeric() |
| '123' | True | True | True |
| '012' | True | True | True |
| 'Ⅷ' | False | True | True |
| '一二三' | False | False | True |
| '¹²³' | False | True | True |
| '🄋' (負圓數字) | False | True | True |
記憶口訣:isdecimal 最嚴格 (僅 0-9 及對應全形) ⊂ isdigit (含上標、圈數字) ⊂ isnumeric (含分數、羅馬、中文數字)。
實際應用場景
# 1. 驗證使用者輸入的純數字 ID (含全形輸入)
def is_valid_id(s):
return s.isnumeric() and len(s) <= 20
# 2. 從混雜文字提取數字區塊 (簡易)
import re
text = '訂單號:No. Ⅷ-2023-001'
# 先用正則切出可能數字段,再用 isnumeric 確認
candidates = re.findall(r'[\d\uFF10-\uFF19ⅰ-ⅿ一-龯]+', text)
numeric_parts = [c for c in candidates if c.isnumeric()]
print(numeric_parts) # ['Ⅷ', '2023', '001']
# 3. 資料清洗:將 numeric 字串轉為 int/float
def to_number(s):
if s.isnumeric():
# 注意:中文數字、羅馬數字無法直接 int()
try:
return int(s)
except ValueError:
return None # 需額外轉換邏輯
return None
轉換中文數字為整數 (進階)
CHINESE_DIGITS = {
'零':0, '一':1, '二':2, '三':3, '四':4, '五':5, '六':6, '七':7, '八':8, '九':9,
'十':10, '百':100, '千':1000, '萬':10000, '億':100000000
}
def chinese_to_int(s):
"""簡易版:支援『一百二十三』格式,不處理複雜嵌套"""
if not s.isnumeric():
return None
total = 0
current = 0
for ch in s:
val = CHINESE_DIGITS.get(ch)
if val is None:
continue
if val >= 10:
if current == 0:
current = 1
total += current * val
current = 0
else:
current = current * 10 + val
total += current
return total
print(chinese_to_int('一百二十三')) # 123
print(chinese_to_int('兩萬三千')) # None (『兩』不在表中)
效能與編碼提醒
isnumeric() 掃描整字串,長字串 (MB 級) 耗時與長度成正比。
- Python 3 字串為 Unicode,直接處理多語系數字無編碼困擾。
- 若僅需判斷 ASCII 0-9,用
s.isascii() and s.isdecimal() (Py3.7+) 或 s.isdigit() 並確認 all('0' <= c <= '9' for c in s) 更快。
copyright ©
萬盛學電腦網 all rights reserved