Yandex

Python String endswith() – Check if a String Ends with Substring


Python String endswith() Method

The endswith() method in Python checks whether a string ends with a specific substring (also called a suffix). It returns True if the string ends with the given value, otherwise False.

Syntax

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

Parameters:

  • suffix – The substring to check for at the end of the string. Can be a single string or a tuple of strings.
  • start (optional) – The starting index to begin searching (default is 0).
  • end (optional) – The ending index to stop searching (default is end of the string).

Returns:

  • True if the string ends with the specified suffix, otherwise False.

Example 1: Basic Usage

text = "hello world"
print(text.endswith("world"))
True

Example 2: Using start and end

text = "python programming"
print(text.endswith("programming", 7))
True

Example 3: Tuple of Suffixes

filename = "report.pdf"
print(filename.endswith((".pdf", ".docx")))
True

This checks if the string ends with .pdf or .docx.

Use Cases

  • Validating file extensions (e.g., .jpg, .pdf)
  • Filtering URLs that end in certain paths
  • Checking strings in data validation tasks

Common Mistakes

  • Passing non-string types as suffix → causes TypeError
  • Not using parentheses: string.endswith is a reference, not a function call

Interview Tip

In coding challenges, endswith() is useful when you need to filter or process strings based on a pattern at the end, like file paths or text parsing.

Summary

  • string.endswith() checks how a string ends
  • Returns True or False
  • Supports optional start and end range
  • Can accept a tuple of possible endings

Practice Problem

Write a program that checks if a user-entered filename ends with ".txt".

filename = input("Enter the file name: ")
if filename.endswith(".txt"):
    print("This is a text file.")
else:
    print("This is not a text file.")


Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M