Python String endswith() Method (original) (raw)
Last Updated : 30 Dec, 2024
The endswith() method is a tool in Python for checking if a string ends with a particular substring. It can handle simple checks, multiple possible endings and specific ranges within the string. This method helps us make our code cleaner and more efficient, whether we’re checking for file extensions, validating URLs or processing text.
Example:
Python `
s = "geeksforgeeks" res = s.endswith("geeks") print(res) # This will print True because the string ends with 'geeks'
`
Table of Content
Syntax of endswith() Method
str.endswith(suffix, start, end)
**Parameters:
- **suffix: Suffix is nothing but a string that needs to be checked.
- **start: Starting position from where suffix is needed to be checked within the string.
- **end: Ending position + 1 from where suffix is needed to be checked within the string.
**Return:
- Returns True if the string ends with the given suffix otherwise return False.
**Note: If start and end index is not provided then by default it takes 0 and length -1 as starting and ending indexes where ending index is not included in our search.
Example 1: Using endswith() with Tuple of Substrings
Sometimes, we might want to check if a string ends with one of several possible substrings. The endswith() method allows us to pass a tuple of substrings. It will return True if the string ends with any one of those substrings.
Python `
s = "geeksforgeeks" res = s.endswith(("geeks", "com", "org")) print(res) # This will print True because 'geeks' is one of the options
`
Example 2: Using endswith() with Start and End Parameters
endswith() method also has optional parameters start and end which allow us to check a substring within a specific part of the string. The start parameter defines where to begin checking and the end parameter defines where to stop checking.
Python `
s = "geeksforgeeks" res = s.endswith("geeks", 5, 15) print(res) # This will print True because 'geeks' is found between position 5 and 15
`
Example 3: Validating File Extensions
When building a file upload system, it’s important to ensure that users upload the correct types of files. For instance, if we only accept images in .jpg and .png formats, we can use endswith() to validate the file extension before processing the file.
Python `
f = "profile_picture.jpg" if f.endswith((".jpg", ".png")): print("File is valid!") else: print("Invalid file type!")
`