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.

Python Courses

Are you enjoying this free tutorial? Please also have a look at my premium courses. They offer a superior user experience with small, easy-to-digest lessons and topics, progress tracking, quizzes to test your knowledge, and practice sessions. Each course will earn you a downloadable course certificate.

The Python Fundamentals Course For Beginners
Now for $29 (from $49)

Python Fundamentals I is a course for beginners that will get you started with Python in no time. Learn all the essentials, test your progress with quizzes and assignments, and bring it all together with the final course project!

Python Course for Beginners

Modules, Packages, And Virtual Environments
Now for $29 (from $49)

Python Fundamentals II covers creating your own modules and packages, using virtual environments and Python package managers to make your life as a programmer easier. Advance your productivity as a Python programmer!

Python Fundamentals 2

Leave a Comment