首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 更多程式設計知識

Python title() 字串方法:單字首字大寫完整教學

     編輯:更多程式設計知識

方法簽名

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
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved