Search code examples
pythonstringlistends-with

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


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?


Solution

  • Try:

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