Convert Strings to Title Case with Python – Fast & Reliable
With this trick, you can quickly convert a Python string to title case. To quote from the Wikipedia article:
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.
Python
- Master Python Strings: Creation, Formatting, and Manipulation
- Mastering Python’s strip() Method: Comprehensive Guide & Practical Examples
- Master Python’s str.count(): How to Count Characters & Substrings with Examples
- Master Python `format()` Strings with Clear Examples
- Python len(): A Practical Guide to Measuring Object Lengths
- Master Python's String.find() Method: Syntax, Examples & Alternatives
- How to Rename Files and Directories in Python with os.rename() – Step-by-Step Guide
- Calculating Averages in Python: A Practical Guide
- Mastering Python Strings: Creation, Access, and Manipulation
- Build a Real-Time Face-Tracking System with Arduino & OpenCV