-2

I have a set of characters, for example: array = ['abc', 'adc, 'cf', 'xyy']

and I have a string: my_word = 'trycf'

I want to write a function that check if the last elements of my_word contain an element of my array. If this is the case, I want to remove it.

I already used endswith such as: if my_word.endswith('cf'): my_word.remove('cf') Then it returns me the word try.

I don't know how to use endswith in the case that I have a list like my array. I know that endswith can take array as parameter (such as if my_word.endswith(array): ) but in this case, I dont know how to take the index of 'cf' from my array to remove it. Can you help me on this please?

Mas A
  • 207
  • 1
  • 11
  • 2
    It looks like you want us to write some code for you. While many users are willing to produce code for a coder in distress, they usually only help when the poster has already tried to solve the problem on their own. A good way to demonstrate this effort is to include the code you've written so far (forming a [mcve]), example input (if there is any), the expected output, and the output you actually get (output, tracebacks, etc.). The more detail you provide, the more answers you are likely to receive. Check the [tour] and [ask]. – TigerhawkT3 Dec 18 '20 at 20:46

2 Answers2

1
for ending in array: # loop through each item in array
    if my_word.endswith(ending): # if our word ends with ending
        my_word = my_word[:len(my_word)-len(ending)] # slice end of our word by the length of ending and assign it back to our word

We decide to slice is, instead of .remove, because .remove may remove match not at the end of the my_word

George
  • 254
  • 2
  • 6
  • An explanation of how this solution works would be more beneficial to users in the long run. Some people (especially beginners) might not understand how this works. – marsnebulasoup Dec 18 '20 at 20:51
  • 1
    Thank you @marsnebulasoup, just starting on stackoverflow. I'll keep that in mind. – George Dec 18 '20 at 21:04
-1

I think what you need is a for loop (https://www.tutorialspoint.com/python/python_for_loop.htm):

array = ['abc', 'adc', 'cf', 'xyy']
my_word = 'trycf'
for suffix in array:
    if my_word.endswith(suffix):
        my_word = my_word[:len(suffix)+1]
        break
print(my_word)
joedeandev
  • 626
  • 1
  • 6
  • 15