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:, 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 Erik van Baaren

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! Writing good articles takes time and effort. Did you like this tutorial? You can buy him a coffee to show your appreciation.

Notify of
Inline Feedbacks
View all comments

No, thanks!