What is the string.title method in Python?
The title method in Python makes the first character of each word uppercase and the remaining characters lowercase.
Syntax
string.title()
Return value
title returns the title cased version of the string, where the first character of each word is uppercase and the remaining characters are lowercase.
Code
Part 1
string = "tHIs"
string.title() # This
Explanation 1
For the string tHIs, the title method will convert the first character to uppercase and the remaining characters to lowercase.
Part 2
string = "tHIs is a TEST"
string.title() # This Is A Test
Explanation 2
For the string tHIs is a TEST, the title method will convert each word’s first character to uppercase and the remaining characters to lowercase.
The word group is separated with the regex
[A-Za-z]+, meaning when a non-alphabetical character occurs in a string, the next part is considered a separate word. For example, in the string “ABC12DEF,” “ABC” and “DEF” are considered two words.
Part 3
string = "tHIs-is#a1TEST*ing"
string.title() # This-Is#A1Test*Ing
Explanation 3
For the string tHIs-is#a1TEST*ing, the words are split as [this, is, a, TEST, ing], and the title function returns This-Is#A1Test*Ing.
Complete code
string = "tHIs"print(string.title()) # Thisstring = "tHIs is a TEST"print(string.title()) # This Is A Teststring = "tHIs-is#a1TEST*ing"print(string.title()) # This-Is#A1Test*Ing