str.isupper() -> bool
回傳 True 當且僅當:
非字母字元 (數字、標點、空白、中文、Emoji) 被忽略。
>> 'HELLO'.isupper()
True
>>> 'HELLO WORLD!'.isupper()
True
>>> 'HELLO 123'.isupper()
True
>>> 'Hello'.isupper()
False
>>> 'HELLO world'.isupper()
False
>>> ''.isupper() # 空字串
False
>>> '12345'.isupper() # 無字母
False
>>> '你好'.isupper() # 漢字非字母
False
>>> 'ẞ'.isupper() # 大寫銳音符
True
>>> 'ß'.isupper() # 小寫銳音符
False
>>> 'STRASSE'.isupper() # 德語慣用全大寫
True
istitle()、islower() 比較| 字串 | isupper() | islower() | istitle() |
|---|---|---|---|
| 'HELLO' | True | False | False |
| 'hello' | False | True | False |
| 'Hello' | False | False | True |
| 'Hello World' | False | False | True |
| 'HELLO WORLD' | True | False | False |
| 'Hello world' | False | False | False |
# 1. 驗證常數命名慣例 (全大寫+底線)
def is_constant_name(name):
return name.isupper() and all(c.isupper() or c.isdigit() or c == '_' for c in name)
print(is_constant_name('MAX_CONNECTIONS')) # True
print(is_constant_name('max_connections')) # False
# 2. 偵測「大寫喊叫」訊息 (聊天室過濾)
def is_shouting(msg):
# 至少 3 個字母且全大寫
letters = [c for c in msg if c.isalpha()]
return len(letters) >= 3 and all(c.isupper() for c in letters)
# 3. 正規化標題:若非標題格式則轉為標題格式
def ensure_title_case(s):
return s if s.istitle() else s.title()
False。ß (U+00DF) 只有小寫,大寫形式為 ẞ (U+1E9E, Unicode 5.1) 或 SS。'ß'.isupper() → False,'ẞ'.isupper() → True。ς (U+03C2) 為小寫,Σ 為大寫。>> 'hello'.upper() # 'HELLO'
>>> 'HELLO'.lower() # 'hello'
>>> 'Hello'.swapcase() # 'hELLO'
>>> 'ß'.upper() # 'SS' (注意: 長度變化)
>>> 'ẞ'.lower() # 'ß'
>>> 'Straße'.casefold() # 'strasse' (適合不分大小寫比較)