Python String endswith() Method
The endswith()
method is used to check whether a string ends with a specified suffix. It returns True
if the string ends with the specified suffix, and False
otherwise.
Syntax
string.endswith(substring, start, end)
Parameters
substring
: The string (or tuple of strings) to check for.
start
(Optional): The starting index from where the check begins. Default is 0
.
end
(Optional): The ending index where the check ends (exclusive). Default is the end of the string.
Return Value
Returns True
if the string ends with the specified suffix, otherwise False
.
Examples
Check if a String Ends With the Specified Suffix
text = "Python is awesome"
print(text.endswith("awesome")) # Output: True
print(text.endswith("amazing")) # Output: False
With start
Parameter
If you only provide the start
parameter, Python checks whether the substring from that index to the end of the string ends with the specified suffix.
text = "Python is awesome"
print(text.endswith("awesome", 10)) # Output: True
print(text.endswith("awesome", 12)) # Output: False
With start
and end
Parameters
If you provide both the start
and end
parameters, Python checks whether the substring from the start
index up to (but not inclucing) the end
index ends with the specified suffix.
text = "Python is awesome"
print(text.endswith("awesome", 10, 16)) # Output: False
print(text.endswith("awesome", 10, 17)) # Output: True
The end
parameter is exclusive meaning the prefix check doesn’t include the character at the end
index.
Using a Tuple of Suffixes
You can provide a tuple of suffixes to the endswith()
method if you want to check whether the string ends with any of the specified suffixes.
text = "Python is awesome"
print(text.endswith(("easy", "amazing", "awesome"))) # Output: True
Case-Sensitivity
The endswith()
method is case-sensitive, meaning it treats uppercase and lowercase letters as distinct characters.
text = "Python is Amazing"
print(text.endswith("amazing")) # Output: False
In this example, the endswith()
method checks if the string ends with the exact lowercase suffix "amazing"
but the string text
ends with the suffix "Amazing"
with an uppercase "A"
. Since the cases don’t match, the method returns False
.
Practical Example
You can use the endswith()
methods to check file extensions.
file = "image.jpg"
if file.endswith(".jpg"):
print("Valid file")
else:
print("Invalid file type")
Output:
Valid file
If you need to check if the string starts with the specified prefix, you can use the startswith()
method.