In this Python tutorial, you will learn how to check if a string ends with a specific substring or suffix string, using string.endswith() method.
Check if a Python string ends with a specific suffix using endswith()
When working with Python strings, you may need to check whether text ends with a particular character, word, file extension, domain suffix, or other substring. Python provides the str.endswith() method for this purpose.
The method performs a suffix check and returns a Boolean value. It returns True when the string ends with the specified suffix and False when it does not.
Python endswith() syntax, parameters, and return value
The syntax of endswith() method is
str.endswith(suffix[, start[, end]])
where suffix is the substring we are looking to match in the main string. start and end arguments are optional. end can be mentioned only if start is provided.
If start is given, the main string from that position is considered for matching with suffix.
If end is given, the main string till that position is considered for matching with suffix.
endswith() returns True if the string ends with the suffix, else endswith() returns False.
Note: You can also provide multiple strings as a tuple for suffix. In that case, endswith() returns true if the string ends with one of the string in suffix. We shall look into this scenario with an example.
The end index is exclusive, just like the end index in Python slicing. Conceptually, text.endswith(suffix, start, end) checks whether the portion text[start:end] ends with suffix.
Python endswith() examples with a single suffix
1. Check if given string ends with specific suffix string
In this example, we have taken a website url as our main string. We shall validate the string, if it ends with suffix com. To validate this, we shall use string.endswith() method as described in the syntax.
Python Program
#the string
website = '[https://www.tutorialkart.com](https://www.tutorialkart.com)'
#suffix
suffix = 'com'
#check if string ends with suffix
isValid = website.endswith(suffix)
print(isValid)
Output
True
Let us check for some of the negative scenarios.
Python Program
#the string
website = '[https://www.tutorialkart.com](https://www.tutorialkart.com)'
#check if string ends with suffix
print(website.endswith('http'))
print(website.endswith('www'))
print(website.endswith('com'))
Output
False
False
True
Check if a Python string ends with any of multiple suffixes
2. Check if given string ends with any of the suffixes
We have noted in the syntax section that you can specify multiple strings for suffix.
In this example, we shall take multiple strings as a tuple for suffix and use endswith() method.
Python Program
#the string
website = '[https://www.tutorialkart.com](https://www.tutorialkart.com)'
#suffix
suffix = ('com','in','us','org')
#check if string ends with suffix
isValid = website.endswith(suffix)
print(isValid)
Output
True
Our string ends with one of the specified strings in suffix.
Passing a tuple is the direct way to test several literal suffixes. For example, it is useful when checking whether a filename has one of several allowed extensions.
filename = "photo.png"
is_image = filename.endswith((".jpg", ".jpeg", ".png"))
print(is_image)
Output
True
Use a Python list of suffixes with endswith()
endswith() accepts either one string or a tuple of strings. If your suffixes are stored in a list, convert the list to a tuple before passing it to the method.
filename = "notes.txt"
suffixes = [".txt", ".md", ".csv"]
print(filename.endswith(tuple(suffixes)))
Output
True
You can also use any() when each suffix needs to be checked separately or when additional conditions are involved.
filename = "notes.txt"
suffixes = [".txt", ".md", ".csv"]
matches = any(filename.endswith(suffix) for suffix in suffixes)
print(matches)
Output
True
Check a selected part of a Python string with endswith()
3. Check if substring of given string ends with given suffix string
In this example, we shall use the parameters start and end mentioned in the syntax above. This lets us check if the substring of given string, defined by the start index and end index, ends with the specified suffix string.
Python Program
#the string
website = '[https://www.tutorialkart.com](https://www.tutorialkart.com)'
#check if string ends with suffix
#start specified
print(website.endswith('com', 8)) #True
#both start and end specified
print(website.endswith('com', 8, 12)) #False
print(website.endswith('us', 15)) #False
Output
True
False
False
The start and end arguments do not modify the original string. They only limit the range used for the suffix comparison.
text = "Python programming"
print(text.endswith("Python", 0, 6))
print(text.endswith("programming", 7))
Output
True
True
Use Python endswith() inside an if statement
Because endswith() returns True or False, it can be used directly as the condition of an if statement.
filename = "report.pdf"
if filename.endswith(".pdf"):
print("PDF file")
else:
print("Not a PDF file")
Output
PDF file
There is no need to write if filename.endswith(".pdf") == True. The Boolean value returned by endswith() can be used directly.
Perform a case-insensitive endswith() check in Python
endswith() is case-sensitive. Therefore, "REPORT.PDF".endswith(".pdf") returns False. For a case-insensitive comparison, normalize the string and suffix before checking them.
filename = "REPORT.PDF"
suffix = ".pdf"
matches = filename.casefold().endswith(suffix.casefold())
print(matches)
Output
True
casefold() is designed for caseless string matching. For simple ASCII filenames, converting both values with lower() is also commonly sufficient.
Check if a Python string ends with a specific character
A suffix does not have to contain several characters. You can pass a one-character string to check the final character.
text = "Hello!"
print(text.endswith("!"))
print(text.endswith("."))
Output
True
False
Use endswith() or regular expressions for Python suffix checks
Use endswith() when the suffix is fixed text, such as ".csv", "ing", or ".com". A regular expression is useful when the ending must match a pattern rather than one or more fixed strings.
For example, the following regular expression checks whether a string ends with one or more digits:
import re
text = "order123"
matches = re.search(r"\d+$", text) is not None
print(matches)
Output
True
For a literal suffix, endswith() communicates the intent more directly and avoids introducing regular-expression syntax.
Python endswith() behavior and edge cases
endswith()returns a Boolean value and does not change the original string.- The suffix comparison is case-sensitive.
- A tuple can be used to check multiple suffixes in one call.
- A list of suffixes should be converted to a tuple before being passed to
endswith(). - The optional
startandendarguments restrict the portion of the string used for the comparison. - An empty suffix matches the end of a string, so
"Python".endswith("")returnsTrue. - Trailing spaces and newline characters are part of the string and can affect the result.
For example, a string that visually appears to end in "done" may actually end in a newline character.
text = "done\n"
print(text.endswith("done"))
print(text.rstrip().endswith("done"))
Output
False
True
Summary of checking suffixes with Python endswith()
Use str.endswith() to determine whether a Python string ends with a specific suffix. Pass a single string for one suffix or a tuple for multiple possible suffixes. Use the optional start and end indexes when only part of the string should be checked. For case-insensitive matching, normalize both values before calling endswith(), and use a regular expression when the ending is defined by a pattern rather than fixed text.
In this Python Tutorial, we learned how to use string.endswith() method to check if a string ends with a suffix string using Python programs.
TutorialKart.com