English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The title() method returns a string where all words start with a capital letter and the rest are lowercase (see istitle()).
The syntax of title() is:
str.title()
The title() method does not take any parameters.
The title() method returns the title case version of a string. This means that the first character of each word is capitalized (if the first character is a letter).
text = 'My favorite number is 25'. print(text.title()) text = '234 k3l2 *43 fun' print(text.title())
When running this program, the output is:
My Favorite Number Is 25. 234 K3L2 *43 Fun
text = "He's an engineer, isn't he?" print(text.title())
When running this program, the output is:
He'S An Engineer, Isn'T He?
When running this program, the output is:
He'S An Engineer, Isn'T He?
title() will also capitalize the first letter after the apostrophe.
To solve this problem, you can use regular expressions as follows:
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))
When running this program, the output is:
He's An Engineer, Isn't He?