萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python 字串方法 isupper() 完整解析:判斷是否全為大寫字母

方法簽名

str.isupper() -> bool

行為定義

回傳 True 當且僅當:

  1. 字串中 至少有一個字母字元 (Unicode 類別 Lu, Ll, Lt, Lm, Lo);
  2. 所有字母字元皆為 大寫。

非字母字元 (數字、標點、空白、中文、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'TrueFalseFalse
'hello'FalseTrueFalse
'Hello'FalseFalseTrue
'Hello World'FalseFalseTrue
'HELLO WORLD'TrueFalseFalse
'Hello world'FalseFalseFalse

實際應用場景

# 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()

Unicode 特殊情況

  • 某些字母無大小寫對應 (如中文、日文假名、阿拉伯字母) → 不計入判斷,若字串僅含此類字元回傳 False。
  • 德語 ß (U+00DF) 只有小寫,大寫形式為 ẞ (U+1E9E, Unicode 5.1) 或 SS。'ß'.isupper() → False,'ẞ'.isupper() → True。
  • 希臘字母 Sigma 末尾形式 ς (U+03C2) 為小寫,Σ 為大寫。

相關轉換方法

>> 'hello'.upper()      # 'HELLO'
>>> 'HELLO'.lower()    # 'hello'
>>> 'Hello'.swapcase() # 'hELLO'
>>> 'ß'.upper()        # 'SS' (注意: 長度變化)
>>> 'ẞ'.lower()        # 'ß'
>>> 'Straße'.casefold() # 'strasse' (適合不分大小寫比較)
copyright © 萬盛學電腦網 all rights reserved