How to check if string or a substring of string ends with suffix in Python?

PythonServer Side ProgrammingProgramming

Python has a method endswith(string) in the String class. This method accepts a suffix string that you want to search and is called on a string object. You can call this method in the following way:

string = 'C:/Users/TutorialsPoint1/'



There is another way to find if a string ends with a given suffix. You can use + '$', string) from the re module(regular expression) to do so. Regex interprets $ as end of line, so if you want to search for a suffix, you need to do the following:

string = 'C:/Users/TutorialsPoint1/'
import re
print(bool('py$', string)))


True returns an object, to check if it exists or not, we need to convert it to a boolean using bool(). You can read more about Python regex <a href="" target="_blank">here</a>.

Updated on 12-Jun-2020 07:21:14