Python String endswith() Method: Check if a String Ends with a Substring | Syntax, Examples & Use Cases

Introduction: Python String endswith() Method

When working with text, you may sometimes need to check how a string finishes. For example, you might want to verify whether a filename ends with ".pdf" or check if a URL ends with a specific path. The Python endswith() Method helps perform this type of check easily.

What it is: It is a built-in Python string method that handles this situation by checking whether a string ends with a specified substring or suffix.

This method:

  • Checks whether a string ends with a specific substring
  • Returns a Boolean result (True or False)
  • Helps validate text patterns at the end of a string

It commonly appears in situations such as:

  • Validating file extensions
  • Checking URL endings
  • Identifying patterns at the end of text

Now let’s examine the syntax, parameters, and return value of the endswith() method before exploring how it works through examples and use cases.

Explore String Methods: Build a stronger understanding of Python strings with the complete Python String Methods List

Python String endswith() Method: Syntax, Parameters & Examples

Before using the method in practical code, it helps to understand its syntax and how each parameter works. The structure is simple, which makes the function easy to remember and apply in different situations.

Syntax

string.endswith(suffix, start=0, end=len(string))

This syntax shows that the method checks whether the string ends with the given suffix. Optional index parameters can limit the portion of the string that is evaluated.

Parameters

Parameter Required Description
suffix Yes The substring (or tuple of substrings) that should appear at the end of the string.
start No The position where the check begins. The default value is 0.
end No The index where the check stops. By default, the entire string is examined.

Return Value

When the Python String endswith() Method performs its check, it simply returns a Boolean result that indicates whether the condition is satisfied.

  • True – The string ends with the specified suffix.
  • False – The string does not end with that suffix.

The method does not modify the original string. It only performs a comparison and returns the result.

A Quick Example:

The following short example demonstrates how the Python String endswith() Method can quickly verify whether a file name contains a specific extension.

filename = "data_report.csv"
print(filename.endswith(".csv"))

#Output: True

Explanation: Here, the method checks the ending of the string and confirms that the filename finishes with .csv. This kind of check is common in scripts that process or filter files.

Examples of Python String endswith() Method

To understand how this method behaves in different situations, it helps to look at several practical examples. These scenarios demonstrate how the method works with domains, file names, and specific string segments.

Example 1: Basic Usage of endswith()

The first example shows a simple case where a string is checked for a specific ending.

text = "learnpython.org"
print(text.endswith(".org"))

#Output: True
Explanation:

The string clearly ends with .org, so the method returns True. This type of check is frequently used when validating domain names or verifying file types.

Example 2: Case Sensitivity Matters

The next example highlights the case-sensitive nature of the Python String endswith() Method.

filename = "report.PDF"
print(filename.endswith(".pdf"))

Output:
# False
Explanation:

Since the method is case-sensitive, .PDF and .pdf are treated as different values. Converting the string to lowercase first allows a case-insensitive check.


print(filename.lower().endswith(".pdf"))  # Returns True

Example 3: Using start and end Parameters

Sometimes it is necessary to evaluate only a particular section of a string rather than the entire text.

message = "Welcome to OpenAI"
print(message.endswith("Open", 11, 15))

#Output:

True
Explanation:

In this example, only the substring between index positions 11 and 15 is examined. Because that portion equals "Open", the method returns True.

Example 4: Using a Tuple of Suffixes

The endswith() method can also accept multiple suffixes using a tuple.

filename = "data.csv"
print(filename.endswith((".csv", ".txt", ".json")))

#Output:

True
Explanation:

Python checks the string against each suffix in the tuple. Since the filename ends with .csv, the method returns True.

Example 5: Checking URLs or File Paths

Another practical use of this method is verifying file paths or web resources.

url = "https://www.example.com/index.html"
print(url.endswith(".html"))

#Output:
True
Explanation:

This example confirms that the URL ends with the .html extension. Such checks are commonly used in web scraping, routing logic, or static site generation tasks.

Common Mistakes to Avoid When Using endswith() in Python

Although the String endswith() Method is simple to use, small misunderstandings can lead to incorrect results. Recognizing these common mistakes helps avoid unnecessary debugging.

1. Ignoring Case Sensitivity

"log.TXT".endswith(".txt")  # False
Correct Approach
"log.TXT".lower().endswith(".txt")  # True
Explanation:

By converting the string to lowercase before performing the check, the comparison becomes case-insensitive. This approach is useful when validating file extensions or URLs.

2. Using in Instead of endswith()

"text.docx" in ".docx"  # Incorrect
Correct Approach
"text.docx".endswith(".docx")  # True
Explanation:

The String endswith() Method is specifically designed for suffix checks. Using it keeps the code clearer and avoids incorrect comparisons.

Practical Use Case: Filtering Files by Extension

A common real-world application of the String endswith() Method is filtering files based on their extensions. This can be done efficiently with list comprehensions.

Example — Filtering File List Using endswith()


files = ["report.docx", "data.csv", "summary.txt", "notes.docx"]
docx_files = [f for f in files if f.endswith(".docx")]
print(docx_files)

#Output

['report.docx', 'notes.docx']
Explanation:

The list comprehension checks each filename and keeps only those that end with .docx. This pattern is commonly used in automation scripts, document processing tools, and data pipelines.

Key Takeaways: Python String endswith() Method

Below is a quick recap of the Python String endswith() method:

  • The endswith() method checks if a string ends with a given suffix.
  • It returns True if the ending matches, otherwise False.
  • You can limit the check using the optional start and end parameters.
  • Multiple suffixes can be checked by passing a tuple.
  • The comparison is case-sensitive.
  • It is commonly used to verify file extensions, URLs, and text patterns.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top