English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python Basic Tutorial

Python Flow Control

Fonctions en Python

Types de données en Python

Python File Operations

Python Objects and Classes

Python Date and Time

Advanced Python Knowledge

Python Reference Manual

Python string title() usage and examples

Python string methods

The title() method returns a string where all words start with a capital letter and the rest are lowercase (see istitle()).

The syntax of title() is:

str.title()

title() parameters

The title() method does not take any parameters.

title() return value

The title() method returns the title case version of a string. This means that the first character of each word is capitalized (if the first character is a letter).

Example1:How does Python title() work?

text = 'My favorite number is 25'.
print(text.title())
text = '234 k3l2 *43 fun'
print(text.title())

When running this program, the output is:

My Favorite Number Is 25.
234 K3L2 *43 Fun

Example2:Title with apostrophe

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

When running this program, the output is:

He'S An Engineer, Isn'T He?

When running this program, the output is:

He'S An Engineer, Isn'T He?

title() will also capitalize the first letter after the apostrophe.

To solve this problem, you can use regular expressions as follows:

Example3:Use regular expressions to capitalize the first letter of each word in the title

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 running this program, the output is:

He's an Engineer, Isn't He?

Python string methods