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.



filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate
# Checking for string match suffix
# using filter() + endswith()
  
# 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))
  
# using filter() + endswith()
# Checking for string match suffix
res = list(filter(test_string.endswith, suff_list)) != []
  
# print result
print("Does string end with any suffix list sublist ? : " + str(res))

chevron_right


Output :

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

 

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate
# Checking for string match suffix
# using endswith()
  
# 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))
  
# using endswith()
# Checking for string match suffix
res = test_string.endswith(tuple(suff_list))
  
# print result
print("Does string end with any suffix list sublist ? : " + str(res))

chevron_right


Output :

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


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.