判斷字串是否全為大寫字母是文字處理常見需求。Python isupper() 方法提供直觀解法:只要字串中至少有一個字母且所有字母皆為大寫即回傳 True。本文詳細說明語法、判斷邏輯、邊界情況與實戰應用。
str.isupper()
回傳值規則:
True。False。非字母字元(數字、符號、空白、中文字)不參與判斷,只檢查字母部分。
#!/usr/bin/python3
# 範例 1:全大寫字母
s1 = "THIS IS STRING EXAMPLE....WOW!!!"
print(s1.isupper()) # True
# 範例 2:含小寫字母
s2 = "THIS is string example....wow!!!"
print(s2.isupper()) # False
# 範例 3:無字母(純數字符號)
s3 = "12345!@#$%"
print(s3.isupper()) # False
# 範例 4:混合中文與大寫英文
s4 = "你好 WORLD"
print(s4.isupper()) # True(中文非字母,不影響)
# 範例 5:混合中文與小寫英文
s5 = "你好 world"
print(s5.isupper()) # False
# 範例 6:空字串
s6 = ""
print(s6.isupper()) # False
# 範例 7:單一大寫字母
s7 = "A"
print(s7.isupper()) # True
| 方法 | 判斷條件 | 範例 True | 範例 False |
|---|---|---|---|
| isupper() | 有字母且全大寫 | "HELLO", "HELLO 123" | "Hello", "123", "" |
| islower() | 有字母且全小寫 | "hello", "hello 123" | "Hello", "123", "" |
| upper() | 轉大寫(回傳新字串) | "HELLO" (from "Hello") | — |
| lower() | 轉小寫(回傳新字串) | "hello" (from "Hello") | — |
| capitalize() | 首字大寫、其餘小寫 | "Hello" (from "hELLO") | — |
| title() | 每單字首字大寫 | "Hello World" (from "hello world") | — |
| swapcase() | 大小寫互換 | "hELLO" (from "Hello") | — |
HTTP_ERROR)、常數命名。UPPER_SNAKE_CASE。# 僅判斷 ASCII 大寫字母
def is_ascii_upper(s):
return any('A' <= c <= 'Z' for c in s) and all(not ('a' <= c <= 'z') for c in s)
# 判斷是否為「大寫開頭」而非全大寫
def is_capitalized(s):
return s[:1].isupper() and s[1:].islower() if s else False
print(is_capitalized("Hello")) # True
print(is_capitalized("HELLO")) # False
print(is_capitalized("hello")) # False
Ä、Ω、Ж 等非 ASCII 大寫字母也會被判斷。s[0].isupper()(注意索引越界)。isupper() 是大小寫判斷的核心方法之一,邏輯清晰:有字母且全大寫。搭配 islower()、upper()、lower() 等轉換方法,能處理絕大多數大小寫相關需求。記住「非字母不參與判斷」與「空字串回傳 False」兩個關鍵點,避免邏輯錯誤。