Open In App

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

Last Updated : 09 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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

Time Complexity : O(n)

Space Complexity : O(n)

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

Time Complexity : O(n)

Space Complexity : O(1)

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

Time Complexity : O(n)

Space Complexity : O(1)

Method #4 : Using split() and in operator

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()
if x[-1] in suff_list:
    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

Time Complexity : O(n)

Space Complexity : O(1)

Method #5 : Using find() and len() methods

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))
 
# Using Loop
for i in suff_list:
    a = test_string.find(i)
    b = len(test_string)-len(i)
    if(a == b):
        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

Time complexity: O(n * m)

Space complexity: O(1)

Method #6 :  Using any()

The any function in Python returns True if any element in an iterable is True, and False otherwise. In this approach, we use a list comprehension to generate a list of boolean values, where each value is True if the test string ends with the current suffix in the list, and False otherwise. The any function is then used to check if any element in the list is True.

Python3




# Python3 code to demonstrate
# Checking for string match suffix
# initializing string
test_string = "GfG is best"
# initializing suffix list
suffix_list = ['best', 'iss', 'good']
# printing original string
print("The original string :"+ str(test_string))
# Use a list comprehension to check if any suffix in the list appears at the end of the test string
result = any(test_string.endswith(suffix) for suffix in suffix_list)
# print result
print("Does string end with any suffix list sublist ? :"+ str(result))
#This code is contributed by Edula Vinay Kumar Reddy


Output

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

Time complexity: O(n), where n is the length of the suffix list
Auxiliary space: O(1)

Method 7:  using operator.countOf() method

Python3




# Python3 code to demonstrate
# Checking for string match suffix
import operator as op
# 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()
if op.countOf(suff_list, x[-1]) > 0:
    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

Time Complexity: O(N)

Auxiliary Space : O(1)

Method 8: Using regular expressions

Python3




import re
 
# Initializing string
test_string = "GfG is best"
 
# Initializing suffix list
suffix_list = ['best', 'iss', 'good']
# printing original string
print("The original string : " + str(test_string))
# Initializing boolean flag
flag = False
 
# Iterating through suffix list
for suffix in suffix_list:
    # Using regular expression to check suffix match
    match = re.search(r'{}$'.format(suffix), test_string)
    if match:
        flag = True
        break
 
# Print result
print("Does string end with any suffix list sublist ? : " + str(flag))
#This code is contributed by Vinay Pinjala.


Output

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

Time Complexity: O(N)

Auxiliary Space : O(1)

Method#9: Using Recursive method.

Python3




def check_suffix(string, suffix_list):
    if not string:
        return False
    words = string.split()
    if not words:
        return False
    if words[-1] in suffix_list:
        return True
    return check_suffix(" ".join(words[:-1]), suffix_list)
 
# 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))
 
res = check_suffix(test_string, suff_list)
 
# print result
print("Does string end with any suffix list sublist ? : " + str(res))
 
#this code contributed by tvsk


Output

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

Time Complexity: O(n)

Auxiliary Space: O(n)



Similar Reads

Check if a column ends with given string in Pandas DataFrame
In this program, we are trying to check whether the specified column in the given data frame ends with the specified string or not. Pandas endswith() is yet another method to search and filter text data in a DataFrame. This method is similar to Pandas.startwith() method. Syntax: string.endswith(value) Creating Dataframe to Check If a Column Ends wi
2 min read
Python - Check whether a string starts and ends with the same character or not (using Regular Expression)
Given a string. The task is to write a regular expression to check whether a string starts and ends with the same character. Examples: Input : abbaOutput : ValidInput : aOutput : ValidInput : abcOutput : InvalidSolution: The input can be divide into 2 cases: Single character string: All single character strings satisfies the condition that they sta
2 min read
Return a boolean array which is True where the string element in array ends with suffix in Python
In this article, we are going to see how we will return a boolean array which is True where the string element in the array ends with a suffix in Python. numpy.char.endswith() numpy.char.endswith() return True if the elements end with the given substring otherwise it will return False. Syntax : np.char.endswith(input_numpy_array,'substring') Parame
2 min read
Python | Check if suffix matches with any string in given list
Given a list of strings, the task is to check whether the suffix matches any string in the given list. Examples: Input: lst = ["Paras", "Geeksforgeeks", "Game"], str = 'Geeks' Output: TrueInput: lst = ["Geeks", "for", "forgeeks"], str = 'John' Output: False Let's discuss a few methods to do the task. Method #1: Using any() The most concise and read
6 min read
How to Return a Boolean Array True Where the String Array Ends with Suffix Using NumPy?
In this article, we will discuss how to return a boolean array that is True where the string element in the array ends with a suffix using NumPy in Python. Example: Check the array ends with Com Input: person_1@abc.com Output: True Input: person_3@xyz.co Output: False In Python, numpy.char module provides a set of vectorized string operations for a
2 min read
Python | Check if any element occurs n times in given list
Given a list, the task is to find whether any element occurs 'n' times in given list of integers. It will basically check for the first element that occurs n number of times. Examples: Input: l = [1, 2, 3, 4, 0, 4, 3, 2, 1, 2], n = 3 Output : 2 Input: l = [1, 2, 3, 4, 0, 4, 3, 2, 1, 2, 1, 1], n = 4 Output : 1 Below are some methods to do the task i
5 min read
Python program to check if any key has all the given list elements
Given a dictionary with list values and a list, the task is to write a Python program to check if any key has all the list elements. Examples: Input : test_dict = {'Gfg' : [5, 3, 1, 6, 4], 'is' : [8, 2, 1, 6, 4], 'best' : [1, 2, 7, 3, 9], 'for' : [5, 2, 7, 8, 4, 1], 'all' : [8, 5, 3, 1, 2]}, find_list = [7, 9, 2] Output : True Explanation : best ha
7 min read
Python | Check if any String is empty in list
Sometimes, while working with Python, we can have a problem in which we need to check for perfection of data in list. One of parameter can be that each element in list is non-empty. Let's discuss if a list is perfect on this factor using certain methods. Method #1 : Using any() + len() The combination of above functions can be used to perform this
6 min read
Python - Check if string starts with any element in list
While working with strings, their prefixes and suffix play an important role in making any decision. Let’s discuss certain ways in which this task can be performed. Example: String = "GfG is best" Input_lis = ['best', 'GfG', 'good'] Output: True Explanation: 'GfG is best' is present in the list. String = "GfG is best" Input_lis = ['Good', 'Bad', 'N
4 min read
Python | Check if any element in list satisfies a condition
Sometimes, while working with Python lists, we can have a problem to filter a list. One of the criteria of performing this filter operation can be checking if any element exists in list that satisfies a condition. Let's discuss certain ways in which this problem can be solved. Method #1 : Using list comprehension This problem can be easily solved u
5 min read
Practice Tags :