Python String endswith() Method with Examples

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:

True

What 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-sensitive

Output:

True
True
True
True
False

Note: 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
True

Passing 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 True

Output:

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

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.

Frequently Asked Questions

What Python version does this tutorial target?
This tutorial targets Python 3.10 or higher. Most examples work on 3.8+, but newer features (match statements, pipe union types, structural pattern matching) need 3.10+. For deep learning content, Python 3.11 is recommended for best performance.
How do I install Python for this tutorial?
Download Python 3.11 or higher from python.org. On Windows, tick ‘Add to PATH’ during install. On Mac use Homebrew (brew install python). On Linux use your package manager or pyenv for version management.
Do I need pip and virtual environments?
Yes. pip comes with Python. For any project beyond a single script, create a virtual environment: python -m venv venv, then activate and pip install dependencies. This keeps project libraries isolated.
Can I use this in a Jupyter notebook or Google Colab?
Most examples run in both. Colab is great for ML tutorials since it provides free GPU access. Jupyter is better for local iterative development. Just paste the code into a cell and run.
Where can I find more Python practice projects?
Browse itsourcecode.com Python Projects for 250+ free capstone-ready systems (sentiment analysis, image classification, chatbots, LangChain apps). Each includes full source code, dataset links, and installation instructions.

Elijah Galero


Programmer & Technical Writer at PIES IT Solution

Elijah Galero is a programmer and writer at PIES IT Solution, author of 175+ tutorials at itsourcecode.com. Specializes in Python error debugging (AttributeError, TypeError, ModuleNotFoundError), Python programming tutorials, and Microsoft Excel how-to guides for BSIT students and productivity learners.

Expertise: Python · Python Errors · Python AttributeError · Python TypeError · ModuleNotFoundError · MS Excel · MS PowerPoint
 · View all posts by Elijah Galero →

Leave a Comment