Python String title()

The title() method returns a string with first letter of each word capitalized; a title cased string.

The syntax of title() is:

str.title()

title() Parameters

The title() method doesn't take any parameters.


Return Value from title()

The title() method returns a title cased version of the string. Meaning, the first character of the each word is capitalized (if the first character is a letter).


Example 1: How Python title() works?

text = 'My favorite number is 25.'
print(text.title())

text = '234 k3l2 *43 fun'
print(text.title())

When you run the program, the output will be:

My Favorite Number Is 25.
234 K3L2 *43 Fun

Example 2: title() with apostrophes

text = "He's an engineer, isn't he?"
print(text.title())

When you run the program, the output will be:

He'S An Engineer, Isn'T He?

When you run the program, the output will be:

He'S An Engineer, Isn'T He?

The title() capitalizes the first letter after apostrophes as well.

To solve this issue, you can use regex as follows:


Example 3: Using Regex to Title Case String

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)

text = "He's an engineer, isn't he?"
print(titlecase(text))

When you run the program, the output will be:

He's An Engineer, Isn't He?