Home > Net >  Remove words from a list that end with a suffix without using endswith()
Remove words from a list that end with a suffix without using endswith()

Time:10-03

I want to write a python function that takes 2 parameters:

  1. List of words and
  2. Ending letters

I want my function to work in such a way that it modifies the original list of words and removes the words which end with the "ending letters" specified.

For example:

list_words = ["hello", "jello","whatsup","right", "cello", "estello"]
ending = "ello"

my_func(list_words, ending)

This should give the following output:

list_words = ["whatsup","right"]

It should pop off all the strings that end with the ending letters given in the second argument of the function.

I can code this function using the .endswith method but I am not allowed to use it. How else can I do this using a loop?

I have written this code but am unsure what's wrong with it:

---python

def my_func(list_words, ending):
    for index in range(len(list_words)):
        if index in range(len(list_words)):
            if list_words[index][-len(ending):] == ending:
                list_words.pop(index)
    return list_words

This code doesn't work for the case where ending = "ion" words = [petition, caution, imitation] the output gives me [caution] when it should give an empty list.

CodePudding user response:

It is always better to not modify the existing list you can get a list which doesn't have the words with the ending specified like below. If you want to have it as a function you can have it in a following manner.

def format_list(words, ending):
    new_list = []
    n = len(ending)
    for word in words:
        if not word[-n:] == ending:
            new_list.append(word)
    return new_list


print(format_list(list_words, ending))

CodePudding user response:

Try:

def my_func(list_words, ending):
    return [word for word in list_words if word[len(x)-len(ending):] != ending]

CodePudding user response:

def filter_words(list_words, ending):
    return [*filter(lambda x: x[-len(ending):] != ending , list_words)]

CodePudding user response:

You can easily check for the last4 characters of a string using string[-4:].

So you can use the below code

list_words = ["hello", "jello","whatsup","right", "cello", "estello"]
ending = "ello"
endLen = len(ending)

def my_func(list_words, ending):
    output = []
    for x in list_words:
        if not x[-endLen:] == ending:
            output.append(x)
    return output

print(my_func(list_words, ending))

You can shorten the function with some list comprehension like this:

def short_func(list_words, ending):
    output = [x for x in list_words if x[-endLen:] != ending]
    return output
print(short_func(list_words, ending))
  • Related