Table of contents
1.
Introduction
2.
Python String endswith() Method Syntax
3.
Parameters
4.
Returns
4.1.
Python
5.
Python String endswith() Method Example
5.1.
Python
6.
Python endswith() With start and end Parameters
6.1.
Python
7.
Real-World Example where endswith() is widely used
8.
Frequently Asked Questions
8.1.
Is the endswith() method case-sensitive?
8.2.
Can I check for multiple suffixes using endswith()?
8.3.
What happens if I provide an empty string as the suffix in endswith()?
9.
Conclusion
Last Updated: Aug 3, 2024
Easy

Python String endswith() Method

Introduction

The endswith() method in Python is an important function for checking if a string ends with a specified suffix. It allows you to quickly determine whether a given string matches a particular ending, making it useful for various text processing tasks. 

Python String endswith() Method

In this article, we'll discuss the endswith() method in detail, like its syntax, parameters, return values & examples. 

Python String endswith() Method Syntax

The syntax for the endswith() method in Python is:

string.endswith(suffix[, start[, end]])


Now, let's discuss the components:
 

- string: The string you want to check for the specified suffix.
 

- suffix: The suffix you want to search for at the end of the string. It can be a single string or a tuple of strings.
 

- start (optional): The starting position from where the search should begin. By default, it starts from the beginning of the string (index 0).
 

- end (optional): The ending position until where the search should be performed. By default, it goes until the end of the string.


The endswith() method returns a Boolean value: True if the string ends with the specified suffix, & False otherwise.

Parameters

The endswith() method accepts the following parameters:

1. suffix (required): This is the suffix you want to check for at the end of the string. It can be a single string or a tuple of strings. If a tuple is provided, the method will return True if the string ends with any of the suffixes in the tuple.
 

2. start (optional): This parameter specifies the starting index from where the search should begin. It allows you to search for the suffix within a specific portion of the string. By default, it starts from the beginning of the string (index 0).
 

3. end (optional): This parameter specifies the ending index until where the search should be performed. It allows you to limit the search to a specific portion of the string. By default, it goes until the end of the string.

Both start & end parameters are optional. If not provided, the method will search the entire string for the specified suffix.

Returns

The endswith() method returns a Boolean value based on whether the string ends with the specified suffix or not.

- If the string ends with the specified suffix, the method returns True.
 

- If the string does not end with the specified suffix, the method returns False.
 

It's important to note that the comparison is case-sensitive. If you want to perform a case-insensitive comparison, you can convert both the string & the suffix to lowercase or uppercase before using the endswith() method.

For example : 

  • Python

Python

text = "Hello, World!"

print(text.endswith("World!"))

print(text.endswith("world!")) 

print(text.endswith(("World!", "Universe!"))) 

print(text.endswith("Hello"))
You can also try this code with Online Python Compiler
Run Code

 

Output: 

True
False
True
False


In the above examples, the endswith() method returns True when the string ends with the specified suffix & False otherwise. It also demonstrates how you can pass a tuple of suffixes to check for multiple endings.

Python String endswith() Method Example


Let's take a look at an example of using the endswith() method in Python. Suppose we have a list of file names & we want to filter out the files with a specific file extension, such as ".txt". Here's how we can achieve that using endswith():

  • Python

Python

file_names = ["document.txt", "image.jpg", "script.py", "readme.txt", "data.csv"]

txt_files = [file for file in file_names if file.endswith(".txt")]

print(txt_files)
You can also try this code with Online Python Compiler
Run Code


Output

["document.txt", "readme.txt"]


In this example, we have a list of file names called `file_names`. We use a list comprehension to create a new list called `txt_files` that contains only the file names ending with the ".txt" extension. The endswith() method is used within the list comprehension to check each file name's suffix.

The resulting `txt_files` list will contain only the file names that end with ".txt", which are "document.txt" & "readme.txt".

Python endswith() With start and end Parameters

The endswith() method also allows you to specify the start and end positions to limit the search range within the string. This can be useful when you want to check for a suffix within a specific portion of the string.

For example : 

  • Python

Python

text = "Hello, World!"

print(text.endswith("World", 7)) 

print(text.endswith("Hello", 0, 5)) 

print(text.endswith("World", 0, 5)) 

print(text.endswith("Hello", 0, len(text))) 
You can also try this code with Online Python Compiler
Run Code


Output: 

True
True
False
False


In the first example, `text.endswith("World", 7)` checks if the substring starting from index 7 (inclusive) until the end of the string ends with "World". Since "World!" starts at index 7, it returns True.

The second example, `text.endswith("Hello", 0, 5)`, checks if the substring from index 0 (inclusive) to index 5 (exclusive) ends with "Hello". It returns True because "Hello" is found at the beginning of the string.

The third example, `text.endswith("World", 0, 5)`, checks if the substring from index 0 to index 5 ends with "World". It returns False because "World" is not found within that substring.

Lastly, `text.endswith("Hello", 0, len(text))` checks if the entire string ends with "Hello". It returns False because the string ends with "World!" and not "Hello".

Real-World Example where endswith() is widely used

One common real-world scenario where the endswith() method is widely used is in file extension validation. Let's consider an example where we have a program that processes different types of files based on their extensions.

Suppose we have a function called `process_file()` that takes a file name as input and performs specific actions based on the file extension. Here's how we can use endswith() to handle different file types:

def process_file(file_name):
    if file_name.endswith(".txt"):
        print(f"Processing text file: {file_name}")
        # Perform text file processing logic here
    elif file_name.endswith((".jpg", ".jpeg", ".png")):
        print(f"Processing image file: {file_name}")
        # Perform image file processing logic here
    elif file_name.endswith(".csv"):
        print(f"Processing CSV file: {file_name}")
        # Perform CSV file processing logic here
    else:
        print(f"Unsupported file type: {file_name}")
# Example usage
process_file("report.txt")
process_file("image.jpg")
process_file("data.csv")
process_file("script.py")


In this example, the `process_file()` function uses the endswith() method to determine the file type based on its extension. It checks for specific file extensions and performs corresponding actions.

- If the file name ends with ".txt", it identifies it as a text file and performs text file processing logic.

- If the file name ends with ".jpg", ".jpeg", or ".png", it identifies it as an image file and performs image file processing logic.

- If the file name ends with ".csv", it identifies it as a CSV file and performs CSV file processing logic.

- If the file name has an unsupported extension, it prints a message indicating that the file type is unsupported.

This example showcases how the endswith() method can be used to validate file extensions and take appropriate actions based on the file type. It provides a clean and efficient way to handle different file formats in a program.

Frequently Asked Questions

Is the endswith() method case-sensitive?

Yes, the endswith() method is case-sensitive. It checks for an exact match of the suffix, including the case.

Can I check for multiple suffixes using endswith()?

Yes, you can pass a tuple of suffixes to the endswith() method to check if the string ends with any of the specified suffixes.

What happens if I provide an empty string as the suffix in endswith()?

If you provide an empty string as the suffix, the endswith() method will always return True because an empty string is considered a suffix of every string.

Conclusion

In this article, we discussed the endswith() method in Python, which allows us to check if a string ends with a specified suffix. We learned about its syntax, parameters, return values & practical examples. We also saw how to use the start & end parameters to limit the search range within the string. Moreover, we looked into a real-world example where endswith() is commonly used for file extension validation.

You can also practice coding questions commonly asked in interviews on Coding Ninjas Code360

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass