title()方法返回一個字符串,所有單詞都是以大寫開始,其余字母均為小寫(見 istitle())。
title()的語法為:
str.title()
title()方法不帶任何參數(shù)。
title()方法返回字符串的標題大小寫版本。意思是,每個單詞的第一個字符都大寫(如果第一個字符是字母)。
text = 'My favorite number is 25.' print(text.title()) text = '234 k3l2 *43 fun' print(text.title())
運行該程序時,輸出為:
My Favorite Number Is 25. 234 K3L2 *43 Fun
text = "He's an engineer, isn't he?" print(text.title())
運行該程序時,輸出為:
He'S An Engineer, Isn'T He?
運行該程序時,輸出為:
He'S An Engineer, Isn'T He?
title()也將撇號后的首字母大寫。
要解決此問題,可以使用正則表達式,如下所示:
import re def titlecase(s): return re.sub(r"[A-Za-z]+('[A-Za-z]+)?", lambda mo: mo.group(0)[0].upper() + mo.group(0)[1:].lower(), s) text = "He's an engineer, isn't he?" print(titlecase(text))
運行該程序時,輸出為:
He's An Engineer, Isn't He?