Proper Title Case creation in Python and C#

Python Logo Unity Logo

Platform: Any/Unity
Language: Python/C#
Requirements: None

Many of you may be familiar with the term Title Case in conjunction with text handling. It is typically used for things, such as book titles, game titles, movie titles, and so forth.
The common perception appears to be that writing a name or headline in title case means to simply capitalize the first letter of each word, like this.

Snow White And The Seven Dwarfs

This, however, is not really how title cases work. The correct application of title cases asks for the capitalization of the first letter of each word, except for certain small words, such as articles and short prepositions. Therefore, the correct way to write the example above would be…

Snow White and the Seven Dwarfs

Unfortunately, most programming languages and libraries get this completely wrong and, by default, offer title case implementations that are simply not correct. To make up for that deficiency, I decided to write my own implementation that I am making available to you here in Python and C#, for use in Unity.

The approach is simple. I create a list containing articles, conjunctions, and prepositions that I am using to identify words in a string that should not be capitalized. Going through the string, word by word, I then create a new output string with the respective words starting with a capital or lowercase letter. Couldn’t be simpler, really, and the advantage of the list is that it can be easily adapted to include certain words for you individual special cases.

Simple steps to put it to work

Here’s a small test-suite to see the implementation at work…

As you will see, it correctly generates the following output, just the way it should be.

How to Interpret "The Hitchhiker's Guide to the Galaxy"
Snow White and the Seven Dwarfs
Newcastle upon Tyne
Brighton on Sea
A Dog's Tale
The Last of the Mohicans
How to Be Smart
About a Boy
Reading 'Fight Club' Through a Postmodernist Lens
How to Interpret “The Hitchhiker's Guide to the Galaxy”
Reading ‘Fight Club’ Through a Postmodernist Lens

Let’s do title cases in Unity

I’ve also implemented the same thing in C#, as an extension to the string class.

Implementing it as an extension of the string class makes the usage of the function a lot easier and more seamless. It allows you to call directly on any string via the string.ProperTitleCase() method.

Here is a small code snippet that shows you how you would use this in a script in Unity.

There you go! Let’s make half-baked title cases a thing of the past.


No comments