Python | Check if string ends with any string in given list
While working with strings, their prefixes and suffix play an important role in making any decision. For data manipulation tasks, we may need to sometimes, check if a string ends with any of the matching strings. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using filter() + endswith() The combination of the above function can help to perform this particular task. The filter method is used to check for each word and endswith method tests for the suffix logic at target list.
Python3
# Python3 code to demonstrate# Checking for string match suffix# using filter() + endswith()# initializing stringtest_string = "GfG is best & quot# initializing suffix listsuff_list = ['best', 'iss', 'good']# printing original stringprint(& quot The original string : & quot + str(test_string))# using filter() + endswith()# Checking for string match suffixres = list(filter(test_string.endswith, suff_list)) != []# print resultprint(& quot Does string end with any suffix list sublist ? : & quot + str(res)) |
Method #2 : Using endswith() As an improvement to the above method, it is not always necessary to include filter method for comparison. This task can be handled solely by supplying a suffix check list as an argument to endswith method as well.
Python3
# Python3 code to demonstrate# Checking for string match suffix# using endswith()# initializing stringtest_string = "GfG is best & quot# initializing suffix listsuff_list = ['best', 'iss', 'good']# printing original stringprint(& quot The original string : & quot + str(test_string))# using endswith()# Checking for string match suffixres = test_string.endswith(tuple(suff_list))# print resultprint(& quot Does string end with any suffix list sublist ? : & quot + str(res)) |
Method #3 : Using split().Splitting the given string and comparing every string of list for matching suffix
Python3
# Python3 code to demonstrate# Checking for string match suffix# initializing resres = False# initializing stringtest_string = "GfG is best"# initializing suffix listsuff_list = ['best', 'iss', 'good']# printing original stringprint("The original string : " + str(test_string))x = test_string.split()for i in suff_list: if(x[-1] == i): res = True# print resultprint("Does string end with any suffix list sublist ? : " + str(res)) |
The original string : GfG is best Does string end with any suffix list sublist ? : True


