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?
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.
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.
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.
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.
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'
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With