Nesper94
Nesper94

Reputation: 23

Use .title() method without converting to lowercase

this is a very simple problem, I need to convert for example the string luis XIV de francia into Luis XIV De Francia in Python. However, if I use the .title() method like this:

'luis XIV de francia'.title()

The result is Luis Xiv De Francia. I don't want XIV to turn into Xiv.

So the question is: Is there something like .title() but that does not transform the other characters (those that are not the first letter of the word) to lowercase?

Thanks for your help.

Upvotes: 2

Views: 810

Answers (2)

Whole Brain
Whole Brain

Reputation: 2167

You can use regular expressions to find the first letter of any word and upper() it:

import re
def custom_title(s):
    return re.sub(r"(?:(?<=\W)|^)\w(?=\w)", lambda x: x.group(0).upper(), s)

custom_title('luis XIV de francia')
# > 'Luis XIV De Francia'

The regex's sub method makes it suitable with larger strings with punctation.

custom_title('luis XIV de francia, something. foo-bar')
# > 'Luis XIV De Francia, Something. Foo-Bar'

Here's another version to also capitalize single letter words:

def custom_title(s):
    return re.sub(r"(?:(?<=\W)|^)\w", lambda x: x.group(0).upper(), s)

Upvotes: 3

Ben Y
Ben Y

Reputation: 1023

The title() method doesn't know that 'xiv' is a roman numeral. The best you can do is segment your string, then title() the relevant pieces, and leave the XIV part as is, then concatenate the pieces together. I think a program will not realize a group of characters might be a roman numeral.

def title_except_all_caps(input):
    parts = [p.title() if p.islower() else p for p in input.split()]
    return ' '.join(parts)

Although the explanation talked about roman numerals, I want you to understand what is going on here. This splits the original string between whitespace, then if it is a lowercase string, apply title() to it. If not, leave it alone. Finally, assemble the resulting string by concatenating the parts using a space as the joiner.

Upvotes: 1

Related Questions