Python str.endswith() function


In Python, the str.endswith() method is used to check whether a string ends with a specified substring. This method returns True if the string ends with the specified substring and False otherwise.

Syntax

str.endswith(suffix[, start[, end]])
  • suffix: A string or a tuple of strings to check against the end of the string.
  • start (optional): The starting index from which to check the suffix. If omitted, the check starts from the beginning of the string.
  • end (optional): The ending index up to which to check the suffix. If omitted, the check goes to the end of the string.

Example Usage

  1. Basic usage:
text = "Hello, world!" result = text.endswith("world!") print(result) # Output: True
  1. Using start and end parameters:
text = "Hello, world!" result = text.endswith("Hello", 0, 5) # Check within index range 0 to 5 print(result) # Output: True result = text.endswith("world!", 0, 12) # Check ending from index 0 to 12 print(result) # Output: True
  1. Checking multiple suffixes:
text = "example.py" result = text.endswith((".py", ".txt")) print(result) # Output: True

Summary

  • Use str.endswith() to determine if a string ends with a specific substring.
  • It can check for multiple suffixes and allows for optional starting and ending indices to refine the check.