Skip to content
Advertisement

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.”

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.

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement