Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

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

I have a string which is basically a file path of a .py file.

string = ‘C:/Users/TutorialsPoint1/~.py’

How do check if it ends in py?


1 Answer
Rajendra Dharmkar

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/~.py'
print(string.endswith('.py'))

OUTPUT

True

There is another way to find if a string ends with a given suffix. You can use re.search(suffix + '$', 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/~.py'
import re
print(bool(re.search('py$', string)))

OUTPUT

True

re.search 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="https://docs.python.org/2/library/re.html" target="_blank">here</a>.

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.