How to Check If a String Ends with a Suffix in Python

PythonPythonBeginner
Practice Now

Introduction

In this lab, you will learn how to check if a string ends with a specific suffix in Python using the endswith() method. This skill is essential for tasks like file type identification and data validation.

The lab guides you through creating a Python script to check for .pdf and .txt suffixes. You'll learn how to use the endswith() method to determine if a string ends with a particular suffix and how to modify the script to check for different suffixes. Further steps will explore checking for multiple suffixes.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/ControlFlowGroup(["Control Flow"]) python(("Python")) -.-> python/PythonStandardLibraryGroup(["Python Standard Library"]) python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python/BasicConceptsGroup -.-> python/strings("Strings") python/ControlFlowGroup -.-> python/conditional_statements("Conditional Statements") python/PythonStandardLibraryGroup -.-> python/data_collections("Data Collections") subgraph Lab Skills python/strings -.-> lab-559571{{"How to Check If a String Ends with a Suffix in Python"}} python/conditional_statements -.-> lab-559571{{"How to Check If a String Ends with a Suffix in Python"}} python/data_collections -.-> lab-559571{{"How to Check If a String Ends with a Suffix in Python"}} end

Learn About String Suffixes

In this step, you will learn about string suffixes and their importance in programming. A string suffix is a substring that occurs at the end of a string. Understanding suffixes is crucial for tasks like file type identification, data validation, and text processing.

Let's start by creating a simple Python script to illustrate string suffixes.

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

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

    ~/project/suffix_example.py
  3. Add the following Python code to the suffix_example.py file:

    filename = "document.pdf"
    
    if filename.endswith(".pdf"):
        print("The file is a PDF document.")
    else:
        print("The file is not a PDF document.")

    This code checks if the string variable filename ends with the suffix .pdf. The endswith() method is used for this purpose.

  4. Save the suffix_example.py file.

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

    python suffix_example.py

    You should see the following output:

    The file is a PDF document.

Now, let's modify the script to check for a different suffix.

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

  2. Modify the code to check for the .txt suffix:

    filename = "document.txt"
    
    if filename.endswith(".txt"):
        print("The file is a text document.")
    else:
        print("The file is not a text document.")
  3. Save the suffix_example.py file.

  4. Run the script again:

    python suffix_example.py

    You should see the following output:

    The file is a text document.

This demonstrates how to use the endswith() method to check for specific suffixes in strings. This is a fundamental technique for many programming tasks.

Use endswith() Method

In this step, you will delve deeper into the endswith() method and explore its various applications. The endswith() method is a powerful tool for checking if a string ends with a specific suffix. It returns True if the string ends with the specified suffix, and False otherwise.

Let's continue with the suffix_example.py file from the previous step. We will modify the script to make it more interactive.

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

  2. Modify the code to prompt the user for a filename and then check if it ends with .txt:

    filename = input("Enter a filename: ")
    
    if filename.endswith(".txt"):
        print("The file is a text document.")
    else:
        print("The file is not a text document.")

    This code uses the input() function to get a filename from the user. Then, it uses the endswith() method to check if the filename ends with .txt.

  3. Save the suffix_example.py file.

  4. Run the script:

    python suffix_example.py

    The script will prompt you to enter a filename.

    Enter a filename:
  5. Enter my_document.txt and press Enter. You should see the following output:

    The file is a text document.
  6. Run the script again and enter my_document.pdf. You should see the following output:

    The file is not a text document.

Now, let's explore the case sensitivity of the endswith() method.

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

  2. Modify the code to check for .TXT (uppercase):

    filename = input("Enter a filename: ")
    
    if filename.endswith(".TXT"):
        print("The file is a text document (uppercase).")
    else:
        print("The file is not a text document (uppercase).")
  3. Save the suffix_example.py file.

  4. Run the script:

    python suffix_example.py
  5. Enter my_document.txt and press Enter. You should see the following output:

    The file is not a text document (uppercase).

This demonstrates that the endswith() method is case-sensitive. To perform a case-insensitive check, you can convert the string to lowercase using the lower() method before using endswith().

filename = input("Enter a filename: ")

if filename.lower().endswith(".txt"):
    print("The file is a text document (case-insensitive).")
else:
    print("The file is not a text document (case-insensitive).")

This modified code will correctly identify my_document.txt as a text document, regardless of the case of the suffix.

Check Multiple Suffixes

In this step, you will learn how to check if a string ends with any one of multiple suffixes. This is useful when you want to identify files based on a list of possible extensions.

Let's modify the suffix_example.py file to check for multiple suffixes.

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

  2. Modify the code to check if the filename ends with either .txt or .pdf:

    filename = input("Enter a filename: ")
    suffixes = (".txt", ".pdf")
    
    if filename.endswith(suffixes):
        print("The file is either a text document or a PDF document.")
    else:
        print("The file is neither a text document nor a PDF document.")

    In this code, we define a tuple called suffixes containing the suffixes we want to check for. The endswith() method can accept a tuple of suffixes as an argument.

  3. Save the suffix_example.py file.

  4. Run the script:

    python suffix_example.py

    The script will prompt you to enter a filename.

    Enter a filename:
  5. Enter my_document.txt and press Enter. You should see the following output:

    The file is either a text document or a PDF document.
  6. Run the script again and enter my_document.pdf. You should see the following output:

    The file is either a text document or a PDF document.
  7. Run the script again and enter my_document.docx. You should see the following output:

    The file is neither a text document nor a PDF document.

Now, let's add another suffix to the tuple.

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

  2. Modify the code to check if the filename ends with .txt, .pdf, or .docx:

    filename = input("Enter a filename: ")
    suffixes = (".txt", ".pdf", ".docx")
    
    if filename.endswith(suffixes):
        print("The file is either a text document, a PDF document, or a Word document.")
    else:
        print("The file is neither a text document, a PDF document, nor a Word document.")
  3. Save the suffix_example.py file.

  4. Run the script:

    python suffix_example.py
  5. Enter my_document.docx and press Enter. You should see the following output:

    The file is either a text document, a PDF document, or a Word document.

This demonstrates how to use the endswith() method with a tuple of suffixes to check for multiple possible file types.

Summary

In this lab, you learned about string suffixes and their importance in programming, particularly for tasks like file type identification. You created a Python script using the endswith() method to check if a filename string ends with specific suffixes like ".pdf" and ".txt".

The lab demonstrated how to modify the script to check for different suffixes and verified the output in each case, illustrating the fundamental technique of using endswith() for string suffix validation.