How to check if string ends with any string in given list in Python

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

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.

 

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

Output :

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

 

Submit Your Programming Assignment Details