Sitelet https://howtodoinjava.com/python-string-functions/string-endswith-method/

Python String endswith(): Check Suffixes with Examples

Check how a Python string ends with str.endswith(), test several suffixes with a tuple, limit the check with start and end, and compare removesuffix().

Python

The Python str.endswith() method returns True when a string ends with the given suffix and False otherwise. File uploads are the typical case, where a script accepts a file only when its name ends with .pdf or .jpg, without slicing the string by hand.

file_name = "report.pdf"
is_pdf = file_name.endswith(".pdf")      # True
is_doc = file_name.endswith(".doc")      # False

Next come several suffixes in one call, a check limited to part of the string, and a comparison with removesuffix(), all tested on Python 3.14.

1. Syntax and Return Value

The method takes one required argument and two optional indexes. The suffix is either a string or a tuple of strings, and start and end work like slice indexes.

str.endswith(suffix[, start[, end]]) -> bool

The return value is a bool. The method returns either True, when the string (or the slice str[start:end]) ends with the suffix or with any suffix in the tuple, or False otherwise. The comparison is case-sensitive, so “beach.JPG”.endswith(“.jpg”) returns False. The method never changes the string, because Python strings are immutable.

2. Checking Several Suffixes with a Tuple

When more than one ending is valid, we pass a tuple, and endswith() returns True if any suffix matches. Calling lower() first makes the check case-insensitive.

photo = "beach.JPG"
is_image = photo.lower().endswith((".jpg", ".png"))   # True

files = ["notes.txt", "cat.png", "song.mp3", "dog.jpg"]
images = [f for f in files if f.endswith((".png", ".jpg"))]   # ['cat.png', 'dog.jpg']

The method accepts a tuple, not a list. When the allowed suffixes come from a list, for example from a config file, we convert the list with tuple().

allowed = [".jpg", ".png"]
bad = photo.endswith(allowed)                  # TypeError: endswith first arg must be str or a tuple of str, not list
ok = photo.lower().endswith(tuple(allowed))    # True

3. Limiting the Check with start and end

With start and end, the method checks only the slice str[start:end]. The end index is exclusive, the same as in slicing.

file_name = "report.pdf.bak"
in_slice = file_name.endswith(".pdf", 0, 10)    # True, checks "report.pdf"
same = file_name[0:10].endswith(".pdf")         # True

Writing the slice next to the call, as in the comment above, makes the result simple to check. A wrong end index is the usual reason a check like this returns False.

4. endswith() vs removesuffix() and Other Options

Since Python 3.9, removesuffix() removes a suffix if it is there and returns the string unchanged otherwise. So we use endswith() to decide something and removesuffix() to get the name without its ending.

name = "report.pdf"
base = name.removesuffix(".pdf")         # 'report'
unchanged = name.removesuffix(".doc")    # 'report.pdf'
empty = name.endswith("")                # True, every string ends with ""
NeedUse
Check one or more endingss.endswith(suffix) or s.endswith((a, b))
Strip a known endings.removesuffix(suffix)
Get any file extensionpathlib.Path(s).suffix, for example ‘.pdf’
Match a pattern, such as digits at the endre.search(r’\d+$’, s)

For the opposite check at the start of a string, see Python startswith().

5. Checking Uploaded File Names

An upload form that accepts only images is the classic use of endswith(). Names arrive with stray spaces and upper-case extensions, so we clean the name before the check and keep the allowed endings in one tuple.

ALLOWED = (".jpg", ".jpeg", ".png")

def is_image(filename):
    return filename.strip().lower().endswith(ALLOWED)

ok = is_image(" Beach.PNG ")           # True
fake = is_image("notes.png.exe")       # False, the real extension is .exe
no_ext = is_image("README")            # False

An extension check looks only at the name, so a renamed file still passes it. For security, the server also checks the file content, for example by opening it with an image library, and treats the extension as a first filter.

6. Questions About endswith()

Suffix checks lead to follow-up questions about file extensions and byte strings.

6.1. How do we get the file name without its extension?

For a known suffix, name.removesuffix(“.pdf”) is enough. For any extension, pathlib.Path(name).stem returns the name without the last suffix, for example “report” for “report.pdf”.

6.2. How do we check whether a string ends with a digit?

The endswith() method needs fixed text, so for a character class we use str.isdigit() on the last character or a regular expression.

import re

ends_digit = "order42"[-1:].isdigit()            # True
ends_num = re.search(r"\d+$", "order42") is not None   # True

6.3. Does endswith() work with bytes?

Yes. A bytes object has its own endswith(), and the suffix must also be bytes, as in data.endswith(b”.gz”). Mixing str and bytes raises TypeError.

6.4. Is endswith() faster than slicing?

Both are fast, but s.endswith(x) avoids a wrong slice length and accepts a tuple, so it is the clearer choice. The slice s[-4:] == “.pdf” breaks as soon as the suffix length changes.

7. Conclusion

A suffix check in Python is one call to endswith(), and a tuple of suffixes covers several file types at once. When we need the name without its ending, removesuffix() does that job, and for any extension pathlib.Path.suffix is the cleaner choice.

8. References

Happy Learning !!

Source Code on Github

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.