Open In App

Python – Remove suffix from string list

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

Sometimes, while working with data, we can have a problem in which we need to filter the strings list in such a way that strings ending with specific suffixes are removed. Let’s discuss certain ways in which this task can be performed. 

Method #1 : Using loop + remove() + endswith() Method

The combination of the above functions can solve this problem. In this, we remove the elements that end with a particular suffix accessed using a loop and return the modified list. 

Python3




# Python3 code to demonstrate working of
# Suffix removal from String list
# using loop + remove() + endswith()
 
# initialize list
test_list = ['allx', 'lovex', 'gfg', 'xit', 'is', 'bestx']
 
# printing original list
print("The original list : " + str(test_list))
 
# initialize suffix
suff = 'x'
 
# Suffix removal from String list
# using loop + remove() + endswith()
for word in test_list[:]:
    if word.endswith(suff):
        test_list.remove(word)
 
# printing result
print("List after removal of suffix elements : "+ str(test_list))


Output

The original list : ['allx', 'lovex', 'gfg', 'xit', 'is', 'bestx']
List after removal of suffix elements : ['gfg', 'xit', 'is']

Time Complexity: O(n)
Auxiliary Space: O(1)

Method #2: Using list comprehension + endswith() Method

This is another way in which this task can be performed. In this, we don’t perform the removal in place, instead, we recreate the list without the elements that match the suffix. 

Python3




# Python3 code to demonstrate working of
# Suffix removal from String list
# using list comprehension + endswith()
 
# initialize list
test_list = ['allx', 'lovex', 'gfg', 'xit', 'is', 'bestx']
 
# printing original list
print("The original list : " + str(test_list))
 
# initialize suff
suff = 'x'
 
# Suffix removal from String list
# using list comprehension + endswith()
res = [ele for ele in test_list if not ele.endswith(suff)]
 
# printing result
print("List after removal of suffix elements : "+ str(res))


Output

The original list : ['allx', 'lovex', 'gfg', 'xit', 'is', 'bestx']
List after removal of suffix elements : ['gfg', 'xit', 'is']

Time Complexity: O(n)
Auxiliary Space: O(n)

Method#3: Using filter function + endswith() Method

This is another way in which a task can be performed. In this, we can create a new list with the help of a filter function which filters out all the string which ends with a defined suffix.

Python3




# Python3 code to demonstrate working of
# Remove prefix strings from list
# using filter + endswith()
 
# initialize suff
suff = 'x'
 
def eva(x):
    return not x.endswith(suff)
# initialize list
test_list = ['allx', 'lovex', 'gfg', 'xit', 'is', 'bestx']
 
# printing original list
print("The original list : " + str(test_list))
 
# Remove prefix strings from list
# using filter + endswith()
res = list(filter(eva, test_list))
 
# printing result
print("List after removal of Kth character of each string : " + str(res))


Output

The original list : ['allx', 'lovex', 'gfg', 'xit', 'is', 'bestx']
List after removal of Kth character of each string : ['gfg', 'xit', 'is']

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #4 :  Without any built-in methods

Python3




# Python3 code to demonstrate working of
# Suffix removal from String list
 
# initialize list
test_list = ["allx", "lovex", "gfg", "xit", "is", "bestx"]
 
# printing original list
print("The original list : " + str(test_list))
 
# initialize suffix
suff = "x"
 
res = []
# Suffix removal from String list
for i in test_list:
    if(i[-1] != suff):
        res.append(i)
 
# printing result
print("List after removal of suffix elements : " + str(res))


Output

The original list : ['allx', 'lovex', 'gfg', 'xit', 'is', 'bestx']
List after removal of suffix elements : ['gfg', 'xit', 'is']

Time Complexity: O(n)
Auxiliary Space: O(n)

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

Python3




# Python3 code to demonstrate working of
# Suffix removal from String list
 
# initialize list
test_list = ["allx", "lovex", "gfg", "xit", "is", "bestx"]
 
# printing original list
print("The original list : " + str(test_list))
 
# initialize suffix
suff = "x"
 
res = []
# Suffix removal from String list
for i in test_list:
    if(i.find(suff)!=len(i)-1):
        res.append(i)
 
# printing result
print("List after removal of suffix elements : " + str(res))


Output

The original list : ['allx', 'lovex', 'gfg', 'xit', 'is', 'bestx']
List after removal of suffix elements : ['gfg', 'xit', 'is']

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #6 : Using lambda functions

Python3




# Python3 code to demonstrate working of
# Remove prefix strings from list
 
# initialize suff
suff = 'x'
 
# initialize list
test_list = ['allx', 'lovex', 'gfg', 'xit', 'is', 'bestx']
 
# printing original list
print("The original list : " + str(test_list))
 
# Remove prefix strings from list
 
res = list(filter(lambda x: x[-1] != suff, test_list))
 
# printing result
print("List after removal of Kth character of each string : " + str(res))


Output

The original list : ['allx', 'lovex', 'gfg', 'xit', 'is', 'bestx']
List after removal of Kth character of each string : ['gfg', 'xit', 'is']

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #7 : Using Regular Expressions
This method uses the regular expression module ‘re’ to match the strings in the list that end with a specific suffix and remove them. Here is an example of how it can be done:

Python3




import re
 
# initialize list
test_list = ['allx', 'lovex', 'gfg', 'xit', 'is', 'bestx']
 
# printing original list
print("The original list : " + str(test_list))
 
# initialize suffix
suff = 'x$'
 
# Suffix removal from String list using regular expressions
res = [x for x in test_list if not re.search(suff, x)]
 
# printing result
print("List after removal of suffix elements : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy


Output

The original list : ['allx', 'lovex', 'gfg', 'xit', 'is', 'bestx']
List after removal of suffix elements : ['gfg', 'xit', 'is']

Time Complexity: O(n)
Auxiliary Space: O(n)

Here we use the function re.search() which returns a match object if there is a match anywhere in the string. We use this function in a list comprehension to filter out the elements in the list that match the regular expression.

Method#8: Using pandas

Python3




import pandas as pd
 
test_list = ['allx', 'lovex', 'gfg', 'xit', 'is', 'bestx']
# printing original list
 
print("The original list : " + str(test_list))
suffix = 'x'
 
# Convert the list of strings to a pandas series
 
s = pd.Series(test_list)
 
# Remove elements with the suffix
 
res = s[~s.str.endswith(suffix)].tolist()
 
print("List after removal of suffix elements :", res)
 
#This code is contributed by Vinay Pinjala.


Output

The original list : ['allx', 'lovex', 'gfg', 'xit', 'is', 'bestx']
List after removal of suffix elements : ['gfg', 'xit', 'is']

Time Complexity: O(n)
Auxiliary Space: O(n)

Method#8: Recursive method

Algorithm:

  1. Define a function remove_strings_with_prefix(lst, prefix) that takes in a list lst and a prefix prefix, and returns a new list that includes only those strings in lst that do not end with the prefix.
  2. Check for the base case where the input list is empty. If the list is empty, return an empty list.
  3. For the recursive case, remove the prefix from the first element in the list, head, and check whether the resulting string still ends with the prefix.
  4. If the head element still ends with the prefix, skip it and recurse on the rest of the list by calling remove_strings_with_prefix(lst[1:], prefix).
  5. If the head element does not end with the prefix, include it in the result by returning [head] + remove_strings_with_prefix(lst[1:], prefix).
  6. Return the resulting list after all recursive calls have completed.

Python3




def remove_strings_with_prefix(lst, prefix):
    # Base case: if the list is empty, return an empty list
    if not lst:
        return []
     
    # Recursive case: remove the prefix from the first element in the list
    head = lst[0]
    if head.endswith(prefix):
        # If the head ends with the prefix, skip it and recurse on the rest of the list
        return remove_strings_with_prefix(lst[1:], prefix)
    else:
        # If the head does not end with the prefix, include it and recurse on the rest of the list
        return [head] + remove_strings_with_prefix(lst[1:], prefix)
 
 
test_list = ['allx', 'lovex', 'gfg', 'xit', 'is', 'bestx']
# printing original list
 
print("The original list : " + str(test_list))
suffix = 'x'
 
 
# Remove elements with the suffix
 
res = remove_strings_with_prefix(test_list,suffix)
 
print("List after removal of suffix elements :", res)
 
#This code is contributed by tvsk.


Output

The original list : ['allx', 'lovex', 'gfg', 'xit', 'is', 'bestx']
List after removal of suffix elements : ['gfg', 'xit', 'is']

The time complexity of this method is O(n), where n is the length of the input list, because it processes each element of the list exactly once. The worst-case time complexity occurs when none of the strings in the input list end with the prefix, in which case the method makes n recursive calls. The best-case time complexity occurs when all the strings in the input list end with the prefix, in which case the method makes only one recursive call.

The space complexity of this method is also O(n), because it creates a new list with at most n elements in the worst case. This is because the method creates a new list for each recursive call and concatenates the resulting lists together at each level of recursion. However, in the best case where all the strings in the input list end with the prefix, the method returns the original input list and therefore does not create any new lists.



Similar Reads

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
Python | Segregate list elements by Suffix
Sometimes, we need to filter the list with the last character of each string in the list. This type of task has many applications in day-day programming and even in the competitive programming domain. Let's discuss certain ways in which this task can be performed. Method #1: Using list comprehension + endswith() In this method, we use list comprehe
8 min read
Python | Append suffix/prefix to strings in list
Sometimes, while working with Python, we can a problem in which we need to pad strings in lists at trailing or leading position. This kind of problem is quite common and can occur in day-day programming or web development. Let's discuss a way in which this task can be performed. Method #1: Using + operator + list comprehension In this task, we just
5 min read
Python - Suffix List Sum
Nowadays, especially in the field of competitive programming, the utility of computing suffix sum is quite popular and features in many problems. Hence, having a one-liner solution to it would possess a great help. Let’s discuss the certain way in which this problem can be solved. Method 1: Using list comprehension + sum() + list slicing This probl
6 min read
Python - Suffix Product in list
Nowadays, especially in the field of competitive programming, the utility of computing suffix product is quite popular and features in many problems. Hence, having a one liner solution to it would possess a great help. Let’s discuss certain way in which this problem can be solved. Method: Using list comprehension + loop + list slicing This problem
5 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 Numeric Suffix in String
Sometimes, while programming, we can have such a problem in which we need to check if any string is ending with a number i.e it has a numeric suffix. This problem can occur in Web Development domain. Let's discuss certain ways in which this problem can be solved. Method #1: Using regex This problem can be solved using regex. The search and group fu
6 min read
Python program to Increment Suffix Number in String
Given a String, the task is to write a Python program to increment the number which is at end of the string. Input : test_str = 'geeks006' Output : geeks7 Explanation : Suffix 006 incremented to 7. Input : test_str = 'geeks007' Output : geeks8 Explanation : Suffix 007 incremented to 8. Method #1 : Using findall() + join() + replace() In this, strat
5 min read
Python program to extract numeric suffix from string
Given a string of characters with digits embedded in it. The task is to write a Python program to extract all the numbers that are trailing, i.e at the suffix of the string. Examples: Input : test_str = "GFG04"Output : 04Explanation : 04 is suffix of string and number hence extracted. Input : test_str = "GFG143"Output : 143Explanation : 143 is suff
7 min read
Python - Remove front K characters from each string in String List
Sometimes, we come across an issue in which we require to delete the first K characters from each string, that we might have added by mistake and we need to extend this to the whole list. This type of utility is common in web development. Having shorthands to perform this particular job is always a plus. Let’s discuss certain ways in which this can
6 min read