Python String title() function returns a title cased version of the string. The first character of the words are in Uppercase and all the remaining characters are in Lowercase.
Python String title()
This function doesn’t accept any argument. Let’s look at some examples of title() function.
Copys = 'Python is Good!' print(s.title()) s = 'PYTHON IS GOOD' print(s.title())
CopyPython Is Good! Python Is Good
This function uses a simple language-independent definition of a word as groups of consecutive letters. So apostrophes (‘) is treated as a word boundary. Let’s see what happens when our string contains an apostrophe.
Copys = "Let's go to Party" print(s.title())
Let'S Go To Party
Most of the times we don’t want this to happen. We can use a regular expression to define a function to convert a string into title cased.
Copyimport re def titlecase(s): return re.sub(r"[A-Za-z]+('[A-Za-z]+)?", lambda mo: mo.group(0).upper() + mo.group(0)[1:].lower(), s) s = "Let's go to Party" print(titlecase(s)) print(titlecase('Python is Good!')) print(titlecase('PYTHON IS GOOD'))
CopyLet's Go To Party Python Is Good! Python Is Good
If you are not familiar with lambda expressions, please read lambda in Python.
Official Documentation: title()