The easiest way to convert a string to title case in Python 3 is using the
title() function. This works in most of the cases except if there are apostrophes or other special characters in the string. See it in the example below;
>>> s = 'how To convErt a strIng to Title casE in pyThon' >>> s.title() 'How To Convert A String To Title Case In Python'
However, if there are special characters in the string, you may need another workaround. Most of the cases the following example will work:
>>> s = u"My friend's dog is named pixie" >>> ' '.join(w.capitalize() for w in s.split()) "My Friend's Dog Is Named Pi̇xie"
Converting UTF-8 Strings Including Letters with Lowercase-Uppercase Differences
This case may sound really strange for most of the people around the world, but in Turkey, we have special letters that fit into this case. For example, in Turkish strings, lowercase i's should convert to İ instead of I. For this type of conversion to work in Python, you need a special library. See it in the example below;
>>> from icu import UnicodeString, Locale >>> tr = Locale("TR") >>> s = UnicodeString("i") >>> print(unicode(s.toUpper(tr))) İ >>> s = UnicodeString("I") >>> print(unicode(s.toLower(tr))) ı >>>
I hope you found this tip useful. Don't forget to visit our Python category archives for more tips on python.