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

A more robust version to convert a string to title case is as follows, and it uses regular expressions:

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.

About the author

Erik is the owner of Python Land and the author of many of the articles and tutorials on this website. He's been working as a professional software developer for 25 years, and he holds a Master of Science degree in computer science. His favorite language of choice: Python!

Leave a Comment