str.endswith()

Checks whether a string ends with a given fragment.

Returns
True or False.
Changes the original
No
On this page

Example

#
Python
files = ["avatar.PNG", "notes.txt", "logo.svg", "photo.jpg"]
images = [f for f in files if f.lower().endswith((".png", ".jpg", ".svg"))]

print(images)
Resultsaved result, you can check it
['avatar.PNG', 'logo.svg', 'photo.jpg']

Definition and usage

#

The endswith() method returns True if the string ends with the given suffix. It is most often used to check file extensions.

Like startswith(), it accepts a tuple of suffixes: name.endswith((".jpg", ".png")) checks several extensions at once.

The comparison is case-sensitive, so "PHOTO.JPG".endswith(".jpg") returns False. Before checking an extension, it is worth converting the filename to lowercase.

Syntax

#
Syntax
string.endswith(suffix, start=0, end=len(string))

Parameters

#
  • suffix

    str or tuple of strings

    A suffix, or several suffixes.
  • end

    int, optional

    The position to stop checking at.

Good practices

#
  • Check extensions after converting the filename to lowercase.
  • For working with paths, pathlib is convenient: Path(name).suffix returns the extension.

Related entries

#

Spotted a mistake or missing an example? Write to us.