Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท String Methods

Python str.title() method

Reference for Python str.title(): capitalize the first letter of each word, why apostrophes break it, and how string.capwords() and manual approaches compare.

The title() method returns a copy of the string in which the first cased letter of each "word" is upper case and all remaining letters are lower case. A word, for this method, is simply a run of letters: any character that is not a letter starts a new word.

That simple rule is both its strength and its weakness. It is fine for quick headings made of plain words, but it gets names with apostrophes and hyphens wrong, and it does not know that small words such as "of" are normally left in lower case.

Python
print("the quick brown fox".title())   # The Quick Brown Fox

Try it

Python Title-casing text

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Where title() goes wrong

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
str.title()

This method takes no parameters.

Return value: a new string in title case.

Raises: nothing.

Usage notes

  • Returns a copy. Strings are immutable, so s.title() leaves s unchanged. Assign the result if you want to keep it.
  • Every non-letter is a word boundary. Digits, underscores, hyphens and apostrophes all end a word, so "they're".title() gives "They'Re" and "snake_case".title() gives "Snake_Case".
  • Rest of each word is lower-cased. "NASA launches".title() becomes "Nasa Launches". Acronyms lose their capitals.
  • Apostrophes: use string.capwords(). It splits on whitespace only, capitalizes each piece with capitalize() and joins with single spaces, so "they're" becomes "They're". The downside is that it collapses runs of whitespace and does not capitalize after hyphens.
  • Not a style-guide title case. No built-in method keeps small words such as "of" or "and" in lower case. Write a small helper, as in the second example.
  • Digraphs. For a few characters Unicode defines a separate title-case form (for example the digraph ว†), which title() uses where it exists.
  • Check without converting. s.istitle() tests whether a string is already in title case.
  • Compare with capitalize(). capitalize() changes only the first character of the whole string; title() changes every word.