Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python convert all-caps into title case without messing with camel case

I’m using python3 and would like to turn strings that contain all caps words (separately or inside a word) into title case (first letter capitalized). I do not want to disrupt one-off capital letters in the middle of a word (camel case), but if there are repeated capitalized letters, I want to keep only the first one capitalized.

Here’s the desired behavior

>>> a = "TITLE BY DeSoto theHUMUNGUSone"
>>> print(myfunc(a))
Title By DeSoto TheHumungusone

In words, "capitalize the beginning of each word and then take any letter that follows a capital letter and make it lower case."

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The str.title() does the initial letters the way I want, but it makes all intra-word letters lower case, rather than just those following the first.

I was playing with a regular expression approach that makes anything that follows an upper case letter lower case, but I kept getting every other letter capitalized.

>Solution :

A regular expression substitution with a lambda is the way to go:

import re

a = "TITLE BY DeSoto theHUMUNGUSone"
print(re.sub('[A-Z]+', lambda x: x.group(0).title(), a))

Output:

Title By DeSoto theHumungusone
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading