Convert a String to Title Case Using Python

With this trick, you can quickly convert a Python string to title case. To quote from the Wikipedia article:

Title case or headline case is a style of capitalization used for rendering the titles of published works or works of art in English. When using title case, all words are capitalized except for “minor” words.”

Title case is often used, both in offline and online printing. This site itself uses title case for all its articles. If you look closely, you’ll notice most websites, newspapers, and magazines are, in fact, using title case.

You can quickly create a title case string in Python; just use the built-in title() method:

>>> title = "string in title case"
>>> title.title()
'String In Title Case'

Unfortunately, this doesn’t work very well:

  • If the string contains apostrophes, it results in this: They’Re Not Working
  • Small words like ‘in’ and ‘no’ should not be title cased but are

Using regular expressions

A more robust version to convert a string to title case is as follows, and it uses regular expressions. You need to import the built-in module re:

import re
def titlecase(s):
    return re.sub(r"[A-Za-z]{3,}('[A-Za-z]+)?", 
       lambda mo: mo.group(0).capitalize(), s)

titlecase("It's great, and no small words")
# "It's Great, And no Small Words"

The regular expression:

  • Matches all words individually, both with and without apostrophes.
  • Doesn’t match words smaller than 3 character, which is usual when title casing headlines

You’re free to further adapt this piece of code to your liking. E.g., you could make it so that a small word like ‘i’ is always capitalized.

Get certified with our courses

Learn Python properly through small, easy-to-digest lessons, progress tracking, quizzes to test your knowledge, and practice sessions. Each course will earn you a downloadable course certificate.

Leave a Comment