1. What is the endswith() Function in Python?
The endswith() method in Python is a built-in string function that checks whether a given string ends with a specific substring or suffix.
It returns True if the string matches the given ending, and False otherwise.
This function is case-sensitive, meaning ‘Python’ and ‘python’ will be treated differently.
Additionally, it supports optional start and end parameters, which let you check only a specific portion of the string.
Example use case:
You can use it to verify file extensions (like .txt or .csv), validate URLs or domain endings, or analyze log entries ending with certain keywords.
2. Purpose of the endswith() Method
The endswith() function is frequently used in:
- It’s a clean, Pythonic way to perform suffix-based string checks without manually slicing strings.
3. Syntax of endswith()
string.endswith(suffix, start=0, end=len(string))
4. Parameter Description: Python String – endswith() Method
| Parameter | Required | Description |
|---|---|---|
| suffix | Yes | The substring (or tuple of substrings) to check at the end of the string. |
| start | No | The position where the search begins. Default is 0. |
| end | No | The position where the search stops (exclusive). Default is the string’s full length. |
Return Value
- Returns True → if the string ends with the given suffix.
- Returns False → if the string does not end with that substring.
Note: The method doesn’t modify the original string — it simply performs a check and returns a Boolean value.
Example Use Cases
filename = "data_report.csv"
print(filename.endswith(".csv"))
#Output: True
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.
5. Practical Examples of the Python endswith() Method
Let’s explore several real-world examples to understand how the Python endswith() method behaves in different scenarios — from basic usage to file handling and case-insensitive checks.
Example 1: Basic Usage of endswith()
text = "learnpython.org"
print(text.endswith(".org"))
#Output: True
Explanation:
The string ends with .org, so the endswith() function returns True.
This is a common check when validating domains or file types that share similar suffix patterns.
Example 2: Case Sensitivity Matters
filename = "report.PDF"
print(filename.endswith(".pdf"))
Output:
# False
Explanation:
The endswith() method is case-sensitive — meaning .PDF and .pdf are treated as different strings.
Tip: To perform a case-insensitive check, convert the string to lowercase first:
print(filename.lower().endswith(".pdf")) # Returns True
Example 3: Using start and end Parameters
message = "Welcome to OpenAI"
print(message.endswith("Open", 11, 15))
#Output:
True
Explanation:
Here, only the substring from index 11 to 15 (“Open”) is checked. Since that segment matches “Open”, the result is True.
This is helpful when working with specific portions of a string rather than the full text.
Example 4: Using a Tuple of Suffixes
filename = "data.csv"
print(filename.endswith((".csv", ".txt", ".json")))
#Output:
True
Explanation:
When multiple suffixes are passed as a tuple, Python checks if the string ends with any of them.
In this case, “data.csv” ends with .csv, so the method returns True.
This approach is often used in file filtering or bulk data import scripts.
url = "https://www.example.com/index.html"
print(url.endswith(".html"))
#Output:
True
Explanation:
This example checks if a URL or file path ends with a specific extension like .html.
It’s commonly used in web scraping, file validation, or static site generation workflows..
6. Common Mistakes to Avoid When Using endswith() in Python
Even though the endswith() method is simple, developers often make small mistakes that lead to incorrect results.
Here are some common pitfalls and how to fix them effectively.
1. Ignoring Case Sensitivity
"log.TXT".endswith(".txt") # False
1. Correct Approach:
"log.TXT".lower().endswith(".txt") # True
Explanation:
By converting the entire string to lowercase first, you ensure a case-insensitive comparison, which is ideal for checking file extensions or URLs where case can vary.
2. Using in Instead of endswith()
"text.docx" in ".docx" # Incorrect
1. Correct Approach:
"text.docx".endswith(".docx") # True
Explanation:
The endswith() function is purpose-built for suffix checking, making it both faster and more reliable than using in for this use case.
Practical Example: Filtering Files by Extension
You can combine endswith() with list comprehension to efficiently filter specific file types from a directory or list.
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:
This example filters and returns only files ending with .docx.
Such logic is widely used in file processing scripts, document automation, and batch data imports.