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`))) 



There is another way to find out whether the string ends with the specified list of suffixes. You can use 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 ( (` (java | xml | py | orld) $ ` , string))) print (bool ( (`(jav a | xml | py | orld) $`, `core java`))) print (bool ( (` (java | xml | py) $ `,` Hello world`))) 


True True False 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