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 whether a string ends with one from a list of suffixes in Python?

List of suffixes = ['txt', 'xml', 'java', 'orld']
string = ‘core java’

How do I check if the above string ends in one from a list of suffixes?


1 Answer
Rajendra Dharmkar

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

string = 'core java'
print(string.endswith(('txt', 'xml', 'java', 'orld')))

OUTPUT

True

There is another way to find if a string ends with a given list of suffixes. You can use re.search from the re module(regular expression) to do so. Regex interprets $ as end of line. We also need to seperate out the suffixes using grouping and | symbol in regex. For example,

import re
string = 'core java'
print(bool(re.search('(java|xml|py|orld)$', string)))
print(bool(re.search('(java|xml|py|orld)$', 'core java')))
print(bool(re.search('(java|xml|py)$', 'Hello world')))

OUTPUT

True
True
False

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.