PythonMastery
Python programs · Strings · beginner

Convert a string to title case in Python

Make the first letter of every word a capital with str.title(). Also shows the apostrophe problem with title() and how string.capwords() avoids it.

Title case means every word starts with a capital letter: "The Quick Brown Fox". The string method title() does this in one call.

The program

python
text = "the quick brown fox"
print(text.title())
output
The Quick Brown Fox

How it works

The apostrophe problem

title() decides where a word starts in a simple way: any letter that comes after a character that is not a letter starts a new word. An apostrophe is not a letter, so the letter after it becomes a capital too:

python
text = "they're reading ada's notes"
print(text.title())
output
They'Re Reading Ada'S Notes

capwords() from the string module splits the text on spaces, capitalises each word, and joins them again. The apostrophes no longer cause a problem:

python
import string

text = "they're reading ada's notes"
print(string.capwords(text))
output
They're Reading Ada's Notes

Both functions make all the other letters small, so "NASA" becomes "Nasa". To keep the rest of each word as it is, see capitalise the first letter of each word.

Learn the idea: Working with Strings