How to Check If a String Is Title Case in Python

PythonPythonBeginner
Practice Now

Introduction

In this lab, you will learn how to check if a string is in title case in Python. The lab begins by explaining the concept of title case, a capitalization style commonly used in titles and headings, where the first letter of each word is capitalized, except for minor words like articles, prepositions, and conjunctions.

You will then create a Python script named title_case.py that includes a function to convert a given string to title case. The script splits the string into words, capitalizes the first letter of each word (excluding minor words), and joins the words back together. Finally, you will run the script and observe the output, demonstrating the conversion of strings to title case.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/ControlFlowGroup(["Control Flow"]) python/BasicConceptsGroup -.-> python/strings("Strings") python/ControlFlowGroup -.-> python/conditional_statements("Conditional Statements") python/FunctionsGroup -.-> python/function_definition("Function Definition") python/FunctionsGroup -.-> python/build_in_functions("Build-in Functions") subgraph Lab Skills python/strings -.-> lab-559580{{"How to Check If a String Is Title Case in Python"}} python/conditional_statements -.-> lab-559580{{"How to Check If a String Is Title Case in Python"}} python/function_definition -.-> lab-559580{{"How to Check If a String Is Title Case in Python"}} python/build_in_functions -.-> lab-559580{{"How to Check If a String Is Title Case in Python"}} end

Understand Title Case

In this step, you will learn about title case, a common capitalization style used in titles and headings. Understanding title case is essential for formatting text correctly and ensuring readability.

Title case refers to a style where the first letter of each word is capitalized, except for certain minor words such as articles (a, an, the), prepositions (of, in, to), and conjunctions (and, but, or). However, the first and last words of the title are always capitalized, regardless of their type.

Let's start by creating a Python script to explore title case.

  1. Open the VS Code editor in the LabEx environment.

  2. Create a new file named title_case.py in the ~/project directory.

    touch ~/project/title_case.py
  3. Open the title_case.py file in the editor.

  4. Add the following Python code to the file:

    def to_title_case(text):
        minor_words = ['a', 'an', 'the', 'of', 'in', 'to', 'and', 'but', 'or']
        words = text.split()
        title_cased_words = []
        for i, word in enumerate(words):
            if i == 0 or i == len(words) - 1 or word not in minor_words:
                title_cased_words.append(word.capitalize())
            else:
                title_cased_words.append(word.lower())
        return ' '.join(title_cased_words)
    
    text1 = "the quick brown fox"
    text2 = "learning python is fun"
    
    print(to_title_case(text1))
    print(to_title_case(text2))

    This code defines a function to_title_case that converts a given string to title case. It splits the string into words, capitalizes the first letter of each word (except for minor words), and then joins the words back together.

  5. Save the title_case.py file.

  6. Run the script using the python command in the terminal:

    python ~/project/title_case.py

    You should see the following output:

    The Quick Brown Fox
    Learning Python Is Fun

    This output demonstrates how the script converts the input strings to title case, capitalizing the first letter of each significant word.

Use istitle() Method

In this step, you will learn how to use the istitle() method in Python to check if a string is in title case. The istitle() method is a built-in string method that returns True if the string is title-cased and False otherwise.

To understand how istitle() works, let's modify the title_case.py script from the previous step.

  1. Open the title_case.py file in the VS Code editor.

  2. Add the following code to the file:

    def to_title_case(text):
        minor_words = ['a', 'an', 'the', 'of', 'in', 'to', 'and', 'but', 'or']
        words = text.split()
        title_cased_words = []
        for i, word in enumerate(words):
            if i == 0 or i == len(words) - 1 or word not in minor_words:
                title_cased_words.append(word.capitalize())
            else:
                title_cased_words.append(word.lower())
        return ' '.join(title_cased_words)
    
    text1 = "the quick brown fox"
    text2 = "Learning Python is fun"
    text3 = to_title_case(text1)
    
    print(text1.istitle())
    print(text2.istitle())
    print(text3.istitle())

    In this code, we are using the istitle() method to check if text1, text2, and text3 are in title case. text1 is in lower case, text2 is partially in title case, and text3 is the result of converting text1 to title case using the to_title_case function from the previous step.

  3. Save the title_case.py file.

  4. Run the script using the python command in the terminal:

    python ~/project/title_case.py

    You should see the following output:

    False
    False
    True

    This output shows that text1 and text2 are not in title case (so istitle() returns False), while text3 is in title case (so istitle() returns True).

Check for Proper Capitalization

In this step, you will learn how to combine the to_title_case function and the istitle() method to check if a given string is properly capitalized according to title case rules. This involves converting the string to title case and then verifying if the converted string is indeed in title case.

Let's continue modifying the title_case.py script from the previous steps.

  1. Open the title_case.py file in the VS Code editor.

  2. Add the following code to the file:

    def to_title_case(text):
        minor_words = ['a', 'an', 'the', 'of', 'in', 'to', 'and', 'but', 'or']
        words = text.split()
        title_cased_words = []
        for i, word in enumerate(words):
            if i == 0 or i == len(words) - 1 or word not in minor_words:
                title_cased_words.append(word.capitalize())
            else:
                title_cased_words.append(word.lower())
        return ' '.join(title_cased_words)
    
    def check_title_case(text):
        title_cased_text = to_title_case(text)
        return title_cased_text.istitle()
    
    text1 = "the quick brown fox"
    text2 = "Learning Python is fun"
    text3 = "The Quick Brown Fox"
    
    print(check_title_case(text1))
    print(check_title_case(text2))
    print(check_title_case(text3))

    In this code, we define a new function check_title_case that takes a string as input, converts it to title case using the to_title_case function, and then uses the istitle() method to check if the converted string is in title case. We then test this function with three different strings: text1, text2, and text3.

  3. Save the title_case.py file.

  4. Run the script using the python command in the terminal:

    python ~/project/title_case.py

    You should see the following output:

    True
    True
    True

    This output shows that text1 and text2 are converted to title case and the istitle() method returns True. text3 is already in title case, and the check_title_case function confirms this.

Summary

In this lab, you begin by understanding the concept of title case, a capitalization style where the first letter of each word is capitalized, except for minor words like articles, prepositions, and conjunctions (with the first and last words always capitalized).

You then create a Python script named title_case.py that defines a function to_title_case to convert a given string to title case. The script splits the string into words, capitalizes the appropriate words, and joins them back together. Finally, you run the script to observe the output, demonstrating the conversion of sample strings to title case.