How to find if an word/string ends with a subword from an array using endswith()?

127 Views Asked by At

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?

2

There are 2 best solutions below

1
On

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)
2
On
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