Skip to content
Related Articles

Related Articles

Python | Check if string ends with any string in given list

View Discussion
Improve Article
Save Article
  • Last Updated : 24 Jun, 2022

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 string
test_string = "
GfG is best & quot
 
# initializing suffix list
suff_list = ['best', 'iss', 'good']
 
# printing original string
print(& quot
       The original string : & quot
       + str(test_string))
 
# using filter() + endswith()
# Checking for string match suffix
res = list(filter(test_string.endswith, suff_list)) != []
 
# print result
print(& 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 string
test_string = "
GfG is best & quot
 
# initializing suffix list
suff_list = ['best', 'iss', 'good']
 
# printing original string
print(& quot
       The original string : & quot
       + str(test_string))
 
# using endswith()
# Checking for string match suffix
res = test_string.endswith(tuple(suff_list))
 
# print result
print(& 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 res
res = False
# initializing string
test_string = "GfG is best"
 
# initializing suffix list
suff_list = ['best', 'iss', 'good']
 
# printing original string
print("The original string : " + str(test_string))
 
x = test_string.split()
for i in suff_list:
    if(x[-1] == i):
        res = True
 
# print result
print("Does string end with any suffix list sublist ? : " + str(res))

Output

The original string : GfG is best
Does string end with any suffix list sublist ? : True

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!