str.title() -> str
返回新字串,將字串中每個單詞的首字母大寫,其餘字母小寫。單詞邊界由非字母字元決定。
s = "this is string example....wow!!!"
print(s.title())
# This Is String Example....Wow!!!
'é'.title() == 'É')。"iPhone".title() == 'Iphone',"C++".title() == 'C++'(+ 非字母)。title() vs capitalize() vs string.capwords()| 方法 | 範例輸入 | 輸出 | 差異 |
|---|---|---|---|
title() | "hello world" | "Hello World" | 每詞首字母大寫 |
capitalize() | "hello world" | "Hello world" | 僅首字母大寫,其餘全小寫 |
string.capwords(s) | "hello world" | "Hello World" | 保留原始空白,分詞邏輯同 split() |
import re
def custom_title(s, sep=r'\s+'):
return re.sub(rf'(?<={sep})(\w)', lambda m: m.group(1).upper(), s.lower())
print(custom_title("hello-world_test")) # Hello-World_Test
str.title() 以單行實現「每詞首字母大寫」,適合標題、人名、標籤格式化。注意其對縮寫、連字符單詞的處理可能不符預期,需時可用 string.capwords() 或正則自定義。