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:
Trueif the string ends with the specified suffix, otherwiseFalse.
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.endswithis 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
TrueorFalse - Supports optional
startandendrange - 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.")
Comments
Loading comments...