str.capitalize() 回傳字串副本,僅將第一個字元轉為大寫,其餘字元轉為小寫。常用於標題正規化、使用者輸入格式化、資料清洗預處理。
語法與參數
str.capitalize()
- 無參數
- 回傳新字串(原字串不變)
- 對 8-bit 字串受 locale 影響(Python 2);Python 3 統一 Unicode 處理
行為細節
| 輸入 | 輸出 | 說明 |
"hello world" | "Hello world" | 首字母大寫,其餘小寫 |
"HELLO WORLD" | "Hello world" | 其餘強制轉小寫 |
"123abc" | "123abc" | 首字元非字母,不變更,其餘小寫 |
" hello" | " hello" | 首字元為空格,空格不變,其餘小寫 |
"" | "" | 空字串回傳空字串 |
實務範例
#!/usr/bin/python
# -*- coding: utf-8 -*-
# 1. 基本用法
text = "this is string example....wow!!!"
print("capitalize():", text.capitalize())
# This is string example....wow!!!
# 2. 使用者輸入正規化
usernames = ["ALICE", "bob", "Charlie", "dAvId"]
normalized = [name.capitalize() for name in usernames]
print(normalized) # ['Alice', 'Bob', 'Charlie', 'David']
# 3. 標題處理(注意:僅第一個單字首字母大寫)
title = "python programming guide"
print(title.capitalize()) # Python programming guide
# 4. 搭配 title() 比較
print(title.title()) # Python Programming Guide (每個單字首字母大寫)
capitalize() vs title() vs upper() 比較
| 方法 | 行為 | 適用場景 |
capitalize() | 首字元大寫,其餘小寫 | 句子首字正規化、單一名稱 |
title() | 每個單字首字母大寫 | 書名、標題、人名 |
upper() | 全部大寫 | 大寫比對、常數命名 |
lower() | 全部小寫 | 不區分大小寫比對、關鍵字 |
swapcase() | 大小寫互換 | 特殊編碼、混淆處理 |
進階:自訂首字大寫邏輯
def smart_capitalize(text, separators=" -_"):
"""支援分隔符的每個單字首字大寫"""
import re
# 以分隔符切分,各段 capitalize,再合併
parts = re.split(f'([{re.escape(separators)}])', text)
return ''.join(p.capitalize() if p not in separators else p for p in parts)
print(smart_capitalize("hello-world_test")) # Hello-World_Test
注意事項
- 非首字元的大寫字母會被強制轉小寫(如
"iPhone".capitalize() → "Iphone"),品牌名稱需特別處理
- 中文字元無大小寫概念,
capitalize() 不影響中文
- Python 3 字串為 Unicode,處理多語言無編碼問題