Python String title() Method



The Python string title() method is used to convert the initial letter of every word in a string to uppercase. If the letter is already in uppercase, the method ignores it. In short, the method converts the string into a titlecase string.

A Titlecase, in literature terms, is a written style used in the names of books, movies, paintings, etc. In this style of writing, the first letter of every major word is capitalised, while minor words remain lowercased. For example, in "Lord of the Rings", the words "Lord" and "Rings" are major, hence why their initial letters are capitalized; while "of" and "the" are minor words, so they remain unchanged.

However, this Python String method will not differentiate between major and minor words; their initial characters are capitalised without bias.

Syntax

Following is the syntax for Python String title() method −

str.title()

Parameters

This method does not accept any parameters.

Return Value

This method returns a copy of the string in which first characters of all the words are capitalized.

Example

When this method is called on a string with all lowercase letters, the return value will be a string with uppercased initial letters in all words.

The following example shows the usage of Python String title() method.

str = "this is string example....wow!!!";
print(str.title())

When we run above program, it produces following result −

This Is String Example....Wow!!!

Example

If we call this method on a string with all uppercase letters, the return value will be a string with lowercased non-initial letters in all words.

Following is an example to convert an input string into a titlecased string using the title() method −

str = "THIS IS A STRING EXAMPLE";
print(str.title())

If we compile and run the given program, the output will be produced as follows −

This Is A String Example

Example

If we call this method on an already titlecased string, the return value will be the original string.

In the following example, we will see the scenario where the title() method is called on an already titlecased string −

str = "This Is A String Example";
print(str.title())

If we compile and run the given program, the output will be produced as follows −

This Is A String Example

Example

If we invoke this method on a string with non-casebased characters, the return value will be the original string.

In the following example, we will see the usage of the title() method when it is called on a string consisting of digits and symbols −

str = "267891!@#$%^&";
print(str.title())

If we compile and run the given program, the output will be produced as follows −

267891!@#$%^&
python_strings.htm
Advertisements