方法簽名
str.title() -> str
行為說明
- 將字串中每個「單字」的第一個字元轉大寫,其餘轉小寫
- 單字分隔依據:非字母數字字元(空白、標點、符號)
- 回傳新字串,原字串不變
基本範例
s = "hello world! python programming"
print(s.title())
# Hello World! Python Programming
s2 = "they're bill's friends"
print(s2.title())
# They'Re Bill'S Friends (注意:' 後字元也會大寫)
已知限制
- 縮寫詞會被錯誤處理:
"USA".title() → "Usa"
- 所有格
's 會變成 'S
- 非 ASCII 字元在某些 Python 版本行為不一
改進版:自訂 title_case
import re
def smart_title(text):
"""保護縮寫詞、所有格的 title case"""
# 簡易版:單字邊界大寫,但保護全大寫詞
words = re.split(r'(\s+)', text) # 保留分隔符
result = []
for w in words:
if w.isupper() and len(w) > 1:
result.append(w) # 保留縮寫
elif w.istitle() or w.islower():
result.append(w.capitalize())
else:
result.append(w)
return ''.join(result)
print(smart_title("hello USA world")) # Hello USA World
相關方法比較
| 方法 | 輸出範例 |
"hello world".capitalize() | Hello world |
"hello world".title() | Hello World |
"hello world".upper() | HELLO WORLD |
"HELLO WORLD".lower() | hello world |