Python Title Case, but leave a pre-existing uppercase

I am looking for a very pythonic path (Python 3.x) to accomplish the following, but haven't come up with yet. If I have the following line:

string = 'this is a test string'

I can write it with:

string.title()

Result:

'This Is A Test String'

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

string = 'Born in the USA'

Using the sample header results in:

string = 'Born in the USA'

Should the results:

'Born In The USA'

I am looking for a way to make a headline but not adjust the existing text in uppercase. Is there any way to do this?

+4
source share
5 answers

It is not clear what result you expect.

If you want to ignore the entire line because it contains uppercase words, check if the line is the first line of the string:

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

, , , :

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

:

>>> string = 'Born in the USA'
>>> ' '.join([w.title() if w.islower() else w for w in string.split()])
'Born In The USA'
+8

:

string = 'born in the USA'

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

:

Born In The USA

, , .

+2

Looks like this is what you want:

def smart_title(s):
    return ' '.join(w if w.isupper() else w.capitalize() for w in s.split())

You can use it, as in the following example:

>>> smart_title('Born in the USA')
'Born In The USA'
+2
source

There is no built-in method, but easy enough to simulate:

def cap(word):
    return word[0].upper() + word[1:]

def title_preserving_caps(string):
    return " ".join(map(cap, string.split(' ')))

string = title_preserving_caps('Born in the USA')
+1
source

Here's a quickie, just ASCII.

In [3]: data = "in UK"

In [4]: titled = data.title()

In [5]: titled
Out[5]: 'In Uk'

In [8]: "".join(map(min, zip(data, titled)))
Out[8]: 'In UK'
+1
source

All Articles