Skip to content
Related Articles

Related Articles

Python String Title method

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 17 Aug, 2022
Improve Article
Save Article

The String title() method in Python is used to convert the first character in each word to uppercase and the remaining characters to lowercase in the string and returns a new string.

Python String title() Method Syntax:

Syntax: str.title()

parameters: title() doesn’t accept any parameter.

Return: str, converted to title case

Python String title() Method Example:





Example 1: Basic usages of Python String title() Method


# conversion from mixed case
str1 = 'geeKs foR geEks'
print(str1, 'converted to using title():', str1.title())
# conversion from all lower case
str4 = 'geeks for geeks'.title()
print(str4, 'converted to using title():', str4.title())
# conversion from all UPPER CASE
str5 = 'WE ARE 1'.title()
print(str5, 'converted to using title():', str5.title())


geeKs foR geEks converted to using title(): Geeks For Geeks
Geeks For Geeks converted to using title(): Geeks For Geeks
We Are 1 converted to using title(): We Are 1

Getting undesired results while using Python String title() Method

Example 1: title() method considers any non-alphabet as a word boundary.


string = "He's smarter."
expected_string = "He's Smarter"
print("Expected:", expected_string, ", Actual:", string.title())


Expected: He's Smarter , Actual: He'S Smarter.

Explanation: The ‘s’ after He’ is converted to Capital letter, because after (apostrophe) string title() method considers the start of a new word, since s is the first letter after (apostrophe), thus it makes ‘s’ as capital letter.

Example 2: Different word boundaries other than space, when using title() Method

Here, even though there are no spaces separated words, still Python String title() method converts the String title case considering ‘-‘(hyphen) as word boundaries.


string = "geeks-for-geeks"
print(string, "converted using title():", string.title())


geeks-for-geeks converted using title(): Geeks-For-Geeks

Word around to unexpected behavior of String title() Method

Example 1: Using Regex to fix the unexpected behavior of Python String title() Method.


import re
def to_title(string):
    regex = re.compile("[a-z]+('[a-z]+)?", re.I)
    return regex.sub(lambda grp:[0].upper() +[1:].lower(),
print(to_title("I won't be working tomorrow."))


I Won't Be Working Tomorrow.

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!