str.title()
Returns a copy of a string with the first letter of every word in capitals and the other letters small, like a book title.
str.title()title() turns "the old man and the sea" into "The Old Man And The Sea": the first letter of each word becomes a capital and every other letter becomes small.
It is a quick way to tidy names and headings typed in all capitals or all small letters.
It has a simple idea of a "word": any run of letters. So after an apostrophe or a digit a new word starts, and "they're" becomes "They'Re". For normal sentences, string.capwords() from the string module only splits at spaces and avoids this.
Return value
A new string in title case.
Examples
1Make a heading
print("the old man and the sea".title())
print("HELLO WORLD".title())The Old Man And The Sea Hello World
2Tidy names
names = ["maria da silva", "OMAR HASSAN", "yuki tanaka"]
for n in names:
print(n.title())Maria Da Silva Omar Hassan Yuki Tanaka
3The apostrophe and digit surprise
print("they're bill's friends".title())
print("3rd place".title())They'Re Bill'S Friends 3Rd Place
Letters after ' or a digit count as the start of a new word.
4A safer choice: string.capwords()
import string
print(string.capwords("they're bill's friends"))
print(string.capwords("3rd place"))They're Bill's Friends 3rd Place
capwords() splits at spaces, capitalises each piece, and joins them again.
Common mistakes
Expecting title() to keep small words small
title() has no grammar rules: words like "and" and "of" get capitals too. Write your own rule if you need them small.
small = {"and", "of", "the"}
words = "the lord of the rings".split()
out = [w if i > 0 and w in small else w.capitalize() for i, w in enumerate(words)]
print(" ".join(out))The Lord of the Rings
Questions people ask
title() vs capitalize(): what is the difference?
title() gives every word a capital; str.capitalize() only the first letter of the whole string.
How do I check if a string is in title case?
Use text.istitle(): "Hello World".istitle() is True.
How do I fix "They'Re"?
Use string.capwords(text), which only treats spaces as word breaks.