Python String title: Complete Introduction

The title() function in python is used to convert the first character in each word to an uppercase and remaining characters to Lowercase in the string and returns a new string.

Python String title()

Python title() is a built-in string handling function that returns a string in which the first letter of the words present in the string is uppercase, and all the other letters of the word are lowercase. If the string contains symbols and numbers, then the 1st number after it is converted to uppercase. We also call the words that have the first letter as uppercase and all other letters as lowercase title cased.

Syntax

string.title()

Here, the string is a variable that is converted to be title-cased.

Parameters

The title() method doesn’t take any parameter and throws an error if any parameter is passed. It is used with a string using a dot operator, and the output string is shown.

Return Value

The method returns a string in which the characters of the words are title-cased.

Example programs on the title() method

Write a program to show the working of the title() method.

// app.py

h1 = "helLo BoYYSSS ANDD gIRLS"
h2 = "I am A BARCA FAN!"
h3 = "I lOvE StRaNgEr ThInGs"
h4 = "I loVe LeaRNinG fRoM aPpDivIdeNd"
h5 = "I lOvE PyThOn"

print("Original string: ", h1)
print("title(): ", h1.title(), "\n")
print("Original string: ", h2)
print("title(): ", h2.title(), "\n")
print("Original string: ", h3)
print("title(): ", h3.title(), "\n")
print("Original string: ", h4)
print("title(): ", h4.title(), "\n")
print("Original string: ", h5)
print("title(): ", h5.title(), "\n")

Output

➜  pyt python3 app.py
Original string:  helLo BoYYSSS ANDD gIRLS
title():  Hello Boyysss Andd Girls

Original string:  I am A BARCA FAN!
title():  I Am A Barca Fan!

Original string:  I lOvE StRaNgEr ThInGs
title():  I Love Stranger Things

Original string:  I loVe LeaRNinG fRoM aPpDivIdeNd
title():  I Love Learning From Appdividend

Original string:  I lOvE PyThOn
title():  I Love Python

➜  pyt

Example 2: Write a program to print two users’ inputted strings using the title().

See the following code.

# app.py

for i in range(0, 2):
    print("Enter the string: ")
    h = input()
    print("Original String: ", h)
    print("title(): ", h.title(), "\n")

Output

➜  pyt python3 app.py
Enter the string:
AppDividend
Original String:  AppDividend
title():  Appdividend

Enter the string:
Ankit
Original String:  Ankit
title():  Ankit

Conclusion

Python string method title() returns a copy of the string in which the first characters of all the words are capitalized.

If you want to get all the strings with the first letter uppercase, you can use the title() function.

That’s it for this tutorial.

See also

Python string upper

Python string capitalize()

Python string casefold()

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.