Use endswith() Function in Python with Example

The `endswith()` method in Python is used to check if a string ends with a specified suffix. It returns `True` if the string ends with the suffix, and `False` otherwise. You can also specify a start and end position to limit the check to a substring.

Syntax

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

– suffix: The suffix to check for. This can be a string or a tuple of strings.
– start (optional): The starting index from where to begin the search.
– end (optional): The ending index where to stop the search.

Examples

Basic Example

text = "Hello, world!"
# Check if the string ends with "world!"
result = text.endswith("world!")
print(result) # Output: True

Example with Tuple of Suffixes

text = "example.txt"
# Check if the string ends with ".txt" or ".md"
result = text.endswith((".txt", ".md"))
print(result) # Output: True

Example with Start and End Parameters

text = "Hello, wonderful world!"
# Check if the substring from index 7 to the end ends with "world!"
result = text.endswith("world!", 7)
print(result) # Output: True
# Check if the substring from index 0 to 12 ends with "Hello, world"
result = text.endswith("Hello, world", 0, 13)
print(result) # Output: True

Explanation

– Basic Example: The `endswith()` method checks if the string `text` ends with the substring `”world!”`. Since it does, the method returns `True`.
– Tuple of Suffixes: The method checks if the string ends with either `.txt` or `.md`. In this case, it ends with `.txt`, so it returns `True`.
– Start and End Parameters: The method checks a specific part of the string. In the first case, it checks from index 7 to the end of the string, and in the second case, it checks from index 0 to 13.