Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Title Case, but leave pre-existing uppercase

I'm looking for a very pythonic way (Python 3.x) of doing the following, but haven't come up with one yet. If I have the following string:

string = 'this is a test string'

I can title case it with:

string.title()

Which results in:

'This Is A Test String'

However, I want to convert if I have the following string:

string = 'Born in the USA'

Applying the title case results in:

string = 'Born In The Usa'

Should results in:

'Born In The USA'

I am looking for a way to do a title case, but not adjust existing upper case text. Is there any way to do this?

like image 207
user2694306 Avatar asked Aug 26 '14 17:08

user2694306


People also ask

How do you capitalize titles in Python?

To make titlecased version of a string, you use the string title() method. The title() returns a copy of a string in the titlecase. The title() method converts the first character of each words to uppercase and the remaining characters in lowercase.

How do you convert a word to a title case in Python?

Python String title() Method The title() method returns a string where the first character in every word is upper case. Like a header, or a title. If the word contains a number or a symbol, the first letter after that will be converted to upper case.

How do you convert a specific letter to uppercase in Python?

Python String upper() In this tutorial, we will learn about the Python String upper() method with the help of examples. The upper() method converts all lowercase characters in a string into uppercase characters and returns it.

How do you make lowercase and uppercase the same in Python?

Artturi Jalli. To convert a Python string to lowercase, use the built-in lower() method of a string. To convert a Python string to uppercase, use the built-in upper() method.


2 Answers

It is unclear what output you are expecting.

If you wanted to ignore the whole string because it contains uppercased words, test if the string is lowercase first:

if string.islower():
    string = string.title()

If you wanted to only ignore specific words that already have uppercase letters, split the string on whitespace, and titlecase only those that are lowercase:

string = ' '.join([w.title() if w.islower() else w for w in string.split()])

Demo of the latter approach:

>>> string = 'Born in the USA'
>>> ' '.join([w.title() if w.islower() else w for w in string.split()])
'Born In The USA'
like image 60
Martijn Pieters Avatar answered Oct 08 '22 22:10

Martijn Pieters


What about:

string = 'born in the USA'

title = "".join([a if a.isupper() else b for a,b in zip(string,string.title())])
print title

Displaying:

Born In The USA

Not very efficient, but will preserve uppercases in the original string, yet allowing to capitalize other words.

like image 40
Sylvain Leroux Avatar answered Oct 08 '22 21:10

Sylvain Leroux