在文字分析、自然語言處理、輸入驗證中,判斷字串是否**完全由字母組成**(無數字、空格、標點)是基礎操作。Python str.isalpha() 方法依據 Unicode 字元屬性執行此檢查,本文完整說明其行為、Unicode 支援、與相關方法的差異及實戰應用。
str.isalpha() -> bool
True 若字串**非空**且**所有字元**皆為 Unicode Letter 類別 (L*);否則 False。''.isalpha() == False。
print("Hello".isalpha()) # True
print("HelloWorld".isalpha()) # True
print("中文".isalpha()) # True (漢字屬 Lo)
print("αβγ".isalpha()) # True (希臘字母)
print("Hello123".isalpha()) # False (含數字)
print("Hello World".isalpha()) # False (含空格)
print("Hello!".isalpha()) # False (含標點)
print("".isalpha()) # False
isalpha() 為 True 的字元屬於 General Category 以 L 開頭:
因此 "漢字".isalpha() == True,"ひらがな".isalpha() == True,"한글".isalpha() == True。
isalnum()、isdigit() 差異| 字串 | isalpha() | isalnum() | isdigit() |
|---|---|---|---|
| "abc" | True | True | False |
| "123" | False | True | True |
| "abc123" | False | True | False |
| "中文" | True | True | False |
| "中文123" | False | True | False |
| "½" | False | True | False |
| "¹²³" | False | True | True (Nd) |
import re
from collections import Counter
def word_freq(text: str) -> Counter:
# 簡單切分:保留字母字元,其他作為分隔符
words = re.findall(r'\b\w+\b', text) # \w 包含底線與數字
# 進一步過濾純字母單字
alpha_words = [w.lower() for w in words if w.isalpha()]
return Counter(alpha_words)
text = "Hello world! 你好世界 123 test-test αβγ"
print(word_freq(text))
# Counter({'hello': 1, 'world': 1, '你好世界': 1, 'test': 1, 'αβγ': 1})
def check_password(pwd: str) -> list[str]:
errors = []
if len(pwd) < 8:
errors.append("長度至少 8 字元")
if not any(ch.isalpha() for ch in pwd):
errors.append("必須包含字母")
if not any(ch.isdigit() for ch in pwd):
errors.append("必須包含數字")
if not any(not ch.isalnum() for ch in pwd):
errors.append("必須包含特殊符號")
return errors
print(check_password("Abc123!")) # []
print(check_password("12345678")) # ['必須包含字母', '必須包含特殊符號']
def sanitize_filename(name: str) -> str:
# 保留字母、數字、底線、連字號、點
return ''.join(ch for ch in name if ch.isalnum() or ch in '_-.')
print(sanitize_filename("我的文件 (1).txt")) # "我的文件1.txt"
若需**嚴格限制 A-Z, a-z**,排除中文、希臘字母等:
import string
def is_ascii_alpha(s: str) -> bool:
return all(ch in string.ascii_letters for ch in s)
# 或正則
import re
ASCII_ALPHA = re.compile(r'^[A-Za-z]+$')
def is_ascii_alpha_re(s): return bool(ASCII_ALPHA.match(s))
print(is_ascii_alpha("Hello")) # True
print(is_ascii_alpha("中文")) # False
print(is_ascii_alpha("αβγ")) # False
_ 不算字母:"a_b".isalpha() == False。變數命名檢查請用 isidentifier()。if s and s.isalpha()。"ABC".isalpha() == True(屬 Lu/Ll)。"e\u0301" (é 組合形式) 兩個字元,isalpha() 視第一個字元為基底字母,回傳 True;但長度為 2。sum(1 for w in words if w.isalpha()) 記數極快。^[A-Za-z]+$ 效能略優於 all(ch in ascii_letters)。掌握 isalpha() 的 Unicode 字母定義與邊界條件,能在詞頻統計、密碼策略、檔名清洗等場合精準判斷「純字母」字串;需 ASCII 限制時請額外加檢查層。