How can I check if a string ends with one of the suffix list in Python?

Python Methods and Functions

Python has an endwith (tuple) method in the String class. This method takes a tuple of strings you want to find and is called on the string object. You can call this method like this:

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

Output:

 True 

There is another way to find out whether the string ends with the specified list of suffixes. You can use re.search from the re (regex) module for this. Regex interprets $ as end of line. We also need to separate the suffixes with grouping and | a character in a regular expression. For example,





 import re string = `core java` print (bool (re.search (` (java | xml | py | orld) $ ` , string))) print (bool (re.search (`(jav a | 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 boolean using bool (). You can read more about Python regular expressions here .







Get Solution for free from DataCamp guru