How to Check if a String Ends with a Pattern in Python?

In this tutorial, I will explain how to check if a string ends with a pattern in Python. As a Python developer working on a project for one of my New York clients, I came across a scenario where I needed to check if a string started with a specific pattern, I explored various Python’s built-in methods to perform this check efficiently. Let us learn more about this topic.

Check if a String Ends with a Pattern in Python

Python provides various methods to achieve this task. Let us see some important techniques.

Read Convert Int to Bytes in Python

1. Use the endswith() Method

Python provides an easy method endswith() to check if a string ends with a specified suffix. This method is part of the string class and is very easy to use.

Syntax

str.endswith(suffix[, start[, end]])
  • suffix: This can be a string or a tuple of strings to check for.
  • start (optional): The position in the string where the check should start.
  • end (optional): The position in the string where the check should end.

Example 1: Check File Extensions

Let’s say you are working with a list of filenames and you want to filter out only those that are CSV files.

filenames = ["data.csv", "report.pdf", "summary.csv", "notes.txt"]
csv_files = [file for file in filenames if file.endswith(".csv")]

print(csv_files)

Output:

['data.csv', 'summary.csv']

I have executed the above example code and added the screenshot below.

String Ends with a Pattern in Python

In this example, we use the endswith() method to check if each filename ends with .csv. The list comprehension filters out the filenames that do not match the pattern.

Read Concatenate String and Float in Python

Example 2: Validate URLs

Suppose you are working on a web application and you need to ensure that certain URLs end with /home.

urls = [
    "https://example.com/home",
    "https://example.com/about",
    "https://example.com/home?user=123",
    "https://example.com/contact"
]

home_urls = [url for url in urls if url.endswith("/home")]

print(home_urls)

Output:

['https://example.com/home']

I have executed the above example code and added the screenshot below.

Check if a String Ends with a Pattern in Python

Here, we use the endswith() method to check if each URL ends with /home. The list comprehension helps filter out URLs that do not match the pattern.

Read Difference Between = and == in Python

2. Use Regular Expressions

While the endswith() method is simple and effective, but there are cases where you might need more flexibility. This is where regular expressions (regex) come into play. Python’s re module provides powerful tools for working with regex.

Example: Use Regex for More Complex Patterns

Let’s consider a scenario where you want to check if a string ends with either .com or .org.

import re

websites = ["https://example.com", "https://nonprofit.org", "https://example.net"]
pattern = re.compile(r"\.(com|org)$")

matching_websites = [site for site in websites if pattern.search(site)]

print(matching_websites)

Output:

['https://example.com', 'https://nonprofit.org']

I have executed the above example code and added the screenshot below.

How to Check if a String Ends with a Pattern in Python

In this example, we use a regex pattern to check if the string ends with .com or .org. The re.compile() function compiles the regex pattern, and the search() method checks if the pattern is found in the string.

Read How to Convert String to List in Python?

Performance Considerations

When working with large datasets or performance-critical applications, it’s important to consider the efficiency of your string operations. The endswith() method is highly optimized and performs well for most use cases. However, if you need to perform complex pattern matching, regular expressions might be more suitable despite their potential performance overhead.

Example: Performance Comparison

Let’s compare the performance of endswith() and regex for a simple pattern check.

import time

# Large list of strings
large_list = ["file{}.txt".format(i) for i in range(1000000)]

# Using endswith()
start_time = time.time()
txt_files = [file for file in large_list if file.endswith(".txt")]
end_time = time.time()
print("endswith() took:", end_time - start_time, "seconds")

# Using regex
pattern = re.compile(r"\.txt$")
start_time = time.time()
txt_files_regex = [file for file in large_list if pattern.search(file)]
end_time = time.time()
print("Regex took:", end_time - start_time, "seconds")

Output:

endswith() took: 0.19353866577148438 seconds
Regex took: 0.46854496002197266 seconds

I have executed the above example code and added the screenshot below.

Check if a String Ends with a Pattern in Python performance compare

In this example, the endswith() method is faster than the regex approach. Therefore, for simple suffix checks, endswith() is generally the better choice.

Read How to Write a List to a File in Python?

Handle Case Sensitivity

By default, the endswith() method is case-sensitive. If you need to perform a case-insensitive check, you can convert the string to lowercase (or uppercase) before using endswith().

Example: Case-Insensitive Check

filenames = ["DATA.CSV", "report.PDF", "summary.csv", "NOTES.TXT"]
csv_files = [file for file in filenames if file.lower().endswith(".csv")]

print(csv_files)

Output:

['DATA.CSV', 'summary.csv']

In this example, we convert each filename to lowercase using the lower() method before checking if it ends with .csv.

Read How to Print a Tuple in Python?

Check Multiple Suffixes

The endswith() method can also accept a tuple of suffixes, allowing you to check for multiple patterns at once.

Example: Multiple Suffixes

filenames = ["data.csv", "report.pdf", "summary.csv", "notes.txt"]
valid_files = [file for file in filenames if file.endswith((".csv", ".txt"))]

print(valid_files)

Output:

['data.csv', 'summary.csv', 'notes.txt']

In this example, we check if each filename ends with either .csv or .txt by passing a tuple of suffixes to the endswith() method.

Read How to Concatenate Tuples in Python?

Conclusion

In this tutorial, I explained how to check if a string ends with a pattern in Python. I covered various methods, like the use of endswith() method for simple checks, regular expressions for more complex patterns, and performance considerations. I also discussed handling case sensitivity and checking multiple suffixes.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.