title()方法返回一个字符串,所有单词都是以大写开始,其余字母均为小写(见 istitle())。
title()的语法为:
str.title()
title()方法不带任何参数。
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?