PythonString methods
str. endswith()
Checks whether a string ends with a given fragment.
- Returns
TrueorFalse.- Changes the original
- No
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,
pathlibis convenient:Path(name).suffixreturns the extension.
Related entries
#Spotted a mistake or missing an example? Write to us.