
Python String title()
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.
s = 'Python is Good!'
print(s.title())
s = 'PYTHON IS GOOD'
print(s.title())
Output:
Python 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.
s = "Let's go to Party"
print(s.title())
Output: 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.
import re
def titlecase(s):
return re.sub(r"[A-Za-z]+('[A-Za-z]+)?",
lambda mo:
mo.group(0)[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'))
Output:
Let'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()