Online Tutorials & Training Materials |
Register Login

Python String Title() Method

|| 0

Python String Title() Method

In python title() function is use to convert the first character of any word present in the string in uppercase and convert rest of the character in lower case and returns new string.



Parameters: No parameters

Return: Returns string with first character of every word in uppercase and remaining character in lower case.


# Python code to explain title() Method 
# Initialize a string with all lowercase characters
str1 = 'python code to explain title method'

# Initialize a string with first uppercase character
str2 = 'Python Code to Explain Title Method'

# Initialize a string with all uppercase character

# Initialize a string with first numaric character
str4 = '1python 2code to 2explain title method'

# Pass strings with title() method
titlestr1 = str1.title()
titlestr2 = str2.title()
titlestr3 = str3.title()
titlestr4 = str4.title()

# Print output
print('String 1: ', str1, ' New 1: ',titlestr1)
print('String 2: ', str2, ' New 2: ',titlestr2)
print('String 3: ', str3, ' New 3: ',titlestr3)
print('String 4: ', str4, ' New 4: ',titlestr4)


String 1:  python code to explain title method  New 1:  Python Code To Explain Title Method
String 2:  Python Code to Explain Title Method  New 2:  Python Code To Explain Title Method
String 3:  PYTHON CODE TO EXPLAIN TITLE METHOD  New 3:  Python Code To Explain Title Method
String 4:  1python 2code to 2explain title method  New 4:  1Python 2Code To 2Explain Title Method


1. Title() method convert first character of every word in Uppercase and rest of character to Lowercase.

2. First character of word in input string is numeric then it will convert second character to Uppercase.

As you can see in the above example that title() function also convert the first character of such word is, as, that, was, on, of, if, in, a, am, thein Upper case. We can avoid such keyword to convert their first character in to uppercase by creating a custom function.


# Python program to explain custom title function

# Define new function
def mytitle(newword):
    # Initialize a list with skip words
    skipWords = ['is', 'as', 'that', 'was', 'on', 'of', 'if', 'in', 'a', 'am', 'the', 'to', 'my']

    # Check if string has skip words
    if newword not in skipWords:

        # Capitalized word
        return newword.capitalize()
    return newword

# Initialize our string to convert to Uppercase
myString = 'This is my python code to explain working of title method'

# Split String with space and save words in list 'myList'
myList = myString.split(" ")

# Pass list 'myList' to mytitle function
nList = map(mytitle, myList)

# Join return string with space
print(" ".join(nList))


This is my Python Code to Explain Working of Title Method