In Python, when we’re working on strings, we might want to check if a string ends with a certain value or not.
That is why this Python endswith() method tutorial will show you how to use the Python string endswith() method with examples.
What is Python endswith()?
Python endswith() is one of the many built-in standard types in Python.
This method is used if a Python string ends with the defined suffix or word.
Then the endswith() method will print or return True; otherwise, False.
The Python documentation for built-in types says that endswith() returns True if the string ends with the specified suffix, otherwise, return False.
Example:
sample = 'Python for free.'
print(sample.endswith('free.'))Output:
TrueWhat does endswith() do in Python?
The endswith() checks the end of the string with the defined value.
If it matches the defined value, it will return True, otherwise False.
What is the use of endswith()?
The string endswith() method is used to find out if a string ends with the characters of another string or not.
Python endswith regex
The endswith() function in Python cannot be used with a regular expression.
Alternatively, you can only search for the end of a string.
An infinite set of matched strings can be described using a regular expression.
For example, ‘*A’ matches every word ending in ‘A’.
This can be hard to compute. Therefore, it makes sense that endswith() does not take regular expressions for performance reasons.
Syntax of string endswith()
The syntax of endswith() is:
str.endswith(suffix[, start[, end]])Parameter values of string endswith()
- suffix (required)- Suffix is simply a string or tuple that must be checked.
- start (optional) – Start position in the string where the suffix is to be checked.
- end (optional) – The end of the string where the suffix must be checked.
Return value from endswith()
endswith() returns a boolean value.- It returns True if a Python string ends with the defined suffix or word.
- It returns False if a Python string doesn’t end with the defined suffix or word.
Endswith() without start and end parameters example program
We will look at several examples of how the Python String endswith() method can be used without the start and end parameters.
sample = "Python is fun and awesome!"
print(sample.endswith('!'))
print(sample.endswith('some!'))
print(sample.endswith('awesome!'))
print(sample.endswith('and awesome!'))
print(sample.endswith('and Awesome!')) # endswith is case-sensitiveOutput:
True
True
True
True
FalseNote: The string endswith() method is case sensitive, ‘awesome’ and ‘Awesome’ are not the same thing.
Endswith() with start and end parameters example program
We will add two more parameters: start and end.
The reason for adding start and end values is that sometimes you need to check a long suffix or text, and at that time, start and end parameters are very important.
sample = "Python is fun and awesome!"
print(sample.endswith('awesome!', 15))
print(sample.endswith('is', 1, 9))
print(sample.endswith('is', 9, 13)) # the search starts and ends at the word "fun."
print(sample.endswith('fun', 9, 13))Output:
True
True
False
TruePassing Tuple to endswith()
Python allows the endswith() method to take a tuple suffix.
endswith() returns True if the string ends on any element of the tuple.
Otherwise, it returns False.
endswith() with Tuple suffix example program
We will look at a few examples of how the Python String endswith() method can be used with the Tuple suffix.
sample = "Learn to code Python for free"
print(sample.endswith(('Python', 'Program'))) # returns False
print(sample.endswith(('for', 'free', 'to'))) # returns True
print(sample.endswith(('for', 'Python'), 0, 20)) # returns TrueOutput:
False True True
Summary
After reading this article, we should now have a good understanding of how to use the Python endswith() method.
If you found the information in this article useful, please consider sharing it with others who may find it useful as well.
If you want additional tutorials Python tutorials
Related Python Tutorials
- Python Uppercase Method With Examples
- Python Rstrip Method With Advanced Examples
- Python Uppercase Method With Examples 2
- Isalpha Python String Method With Advanced Examples
- Python Ceiling Method With Examples
- Python Private Method With Examples
Common use cases for Python String endswith() Method
- Data pipelines. Python is the standard for ETL, data analysis, and ML workflows.
- Web development. Django and FastAPI power modern web backends and APIs.
- Automation and scripting. System administration, file processing, web scraping, and cron jobs.
- Machine learning. scikit-learn, PyTorch, TensorFlow, Hugging Face for AI/ML projects.
- Educational tools. Python’s readability makes it the go-to teaching language.
Working code example
from typing import Optional
def process_data(items: list[dict]) -> Optional[dict]:
"""Process a list of items and return summary stats."""
if not items:
return None
return {
"count": len(items),
"total": sum(item.get("value", 0) for item in items),
"avg": sum(item.get("value", 0) for item in items) / len(items),
}
# Usage
data = [{"value": 10}, {"value": 20}, {"value": 30}]
summary = process_data(data)
print(summary) # {'count': 3, 'total': 60, 'avg': 20.0}
Best practices
- Use type hints. list[dict], Optional[str], and TypedDict make code self-documenting and enable static analysis.
- Follow PEP 8. Consistent style improves readability. Use black or ruff to auto-format.
- Prefer f-strings. f”{value}” is cleaner than str.format() or % formatting.
- Write tests with pytest. Aim for 70%+ coverage on business-critical modules.
- Use ruff or pylint. Static analysis catches many bugs before code runs.
Common pitfalls
- Mutable default arguments. def f(x=[]) reuses the same list across calls. Use x=None then check.
- Integer division. 5/2 gives 2.5 in Python 3. Use // for floor division.
- Missing self on methods. Class methods need self as first parameter.
- Late binding closures. Loops that create lambdas can capture variables late.
