Open In App

Convert string to title case in Python

Improve
Improve
Like Article
Like
Save
Share
Report

Title case is a style of writing that is used for the titles of articles, books, movies, and other works. The rules for writing in title case are:

1) Always capitalize the first word.
2) Capitalize all words except the following parts of speech:

  • articles – a, an, the
  • coordinating conjunctions – and, but, for, nor, or, so, yet
  • short prepositions – to, in, up, from etc

Examples:

Input : The quick brown fox jumps over the lazy dog.
Output : The Quick Brown Fox Jumps over the Lazy Dog.

Input : A tale of two cities
Output : A Tale of Two Cities

Algorithm :

  1. Make a list of all the words that have to be in lower case.
  2. For every word in the input, check whether it is in the above list or not.
  3. If yes then ignore the word, if no then capitalize its first character.

The implementation of the above algorithm is:




# Function to convert into title case
def generateTitleCase(input_string):
      
    # list of articles
    articles = ["a", "an", "the"]
      
    # list of coordinating conjunctins
    conjunctions = ["and", "but",
                    "for", "nor",
                    "or", "so",
                    "yet"]
      
    # list of some short articles
    prepositions = ["in", "to", "for"
                    "with", "on", "at",
                    "from", "by", "about",
                    "as", "into", "like",
                    "through", "after", "over",
                    "between", "out", "against"
                    "during", "without", "before",
                    "under", "around", "among",
                    "of"]
      
    # merging the 3 lists
    lower_case = articles + conjunctions + prepositions
      
    # variable declaration for the output text 
    output_string = ""
      
    # separating each word in the string
    input_list = input_string.split(" ")
      
    # checking each word
    for word in input_list:
          
        # if the word exists in the list
        # then no need to capitalize it
        if word in lower_case:
            output_string += word + " "
              
        # if the word does not exists in
        # the list, then capitalize it
        else:
            temp = word.title()
            output_string += temp + " "
              
      
    return output_string
  
# Driver code  
if __name__=='__main__':  
    input_text1 = "The quick brown fox jumps over the lazy dog."
    input_text2 = "A tale of two cities"
      
    print(generateTitleCase(input_text1)) 
    print(generateTitleCase(input_text2)) 


Output :

The Quick Brown Fox Jumps over the Lazy Dog. 
A Tale of Two Cities 


Last Updated : 17 May, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads