How to Use endswith in Python: Syntax and Examples
In Python, use the
endswith() method on a string to check if it ends with a specific suffix or any suffix from a tuple. It returns True if the string ends with the given suffix, otherwise False.Syntax
The endswith() method is called on a string and takes one or two arguments:
- suffix: A string or a tuple of strings to check if the original string ends with any of them.
- start (optional): The position in the string to start checking.
- end (optional): The position in the string to stop checking.
The method returns True if the string ends with the suffix, otherwise False.
python
string.endswith(suffix[, start[, end]])
Example
This example shows how to use endswith() to check if a string ends with a specific suffix or any suffix from a tuple.
python
filename = "report.pdf" # Check if filename ends with '.pdf' print(filename.endswith('.pdf')) # True # Check if filename ends with either '.doc' or '.pdf' print(filename.endswith(('.doc', '.pdf'))) # True # Using start and end parameters text = "Hello world!" print(text.endswith('world!', 0, 12)) # True print(text.endswith('world', 0, 11)) # False
Output
True
True
True
False
Common Pitfalls
Common mistakes when using endswith() include:
- Passing a list instead of a tuple for multiple suffixes, which causes a
TypeError. - Forgetting that
endswith()is case-sensitive. - Misusing the
startandendparameters, which define the substring to check, not the suffix itself.
python
filename = "example.TXT" # Wrong: using list instead of tuple # print(filename.endswith(['.txt', '.doc'])) # Raises TypeError # Right: use tuple print(filename.endswith(('.TXT', '.DOC'))) # True # Case-sensitive check print(filename.endswith('.txt')) # False # Using start and end incorrectly text = "Hello world!" # This checks substring from index 6 to 11 print(text.endswith('world', 6, 11)) # True # But this will be False because substring is 'world!' print(text.endswith('world', 6, 12)) # False
Output
True
False
True
False
Quick Reference
| Usage | Description |
|---|---|
| string.endswith(suffix) | Returns True if string ends with suffix |
| string.endswith((s1, s2)) | Returns True if string ends with any suffix in tuple |
| string.endswith(suffix, start, end) | Checks substring from start to end for suffix |
Key Takeaways
Use
endswith() to check if a string ends with a specific suffix or any from a tuple.endswith() is case-sensitive and returns a boolean.Pass a tuple, not a list, when checking multiple suffixes.
Optional start and end parameters limit the substring checked.
Common errors include wrong argument types and misunderstanding start/end usage.