Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Python

Convert Strings to Title Case with Python – Fast & Reliable

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:

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:

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

  1. Master Python Strings: Creation, Formatting, and Manipulation
  2. Mastering Python’s strip() Method: Comprehensive Guide & Practical Examples
  3. Master Python’s str.count(): How to Count Characters & Substrings with Examples
  4. Master Python `format()` Strings with Clear Examples
  5. Python len(): A Practical Guide to Measuring Object Lengths
  6. Master Python's String.find() Method: Syntax, Examples & Alternatives
  7. How to Rename Files and Directories in Python with os.rename() – Step-by-Step Guide
  8. Calculating Averages in Python: A Practical Guide
  9. Mastering Python Strings: Creation, Access, and Manipulation
  10. Build a Real-Time Face-Tracking System with Arduino & OpenCV