-2

我有一组字符,例如: array = ['abc', 'adc, 'cf', 'xyy']

我有一个字符串:my_word = 'trycf'

我想编写一个函数来检查 my_word 的最后一个元素是否包含我的数组的元素。如果是这种情况,我想删除它。

我已经使用过endswith,例如: if my_word.endswith('cf'): my_word.remove('cf') 然后它返回给我这个词try

endswith如果我有一个类似我的列表,我不知道如何使用array。我知道 endwith 可以将数组作为参数(例如if my_word.endswith(array):),但在这种情况下,我不知道如何'cf'从我的数组中获取索引来删除它。你能帮我解决这个问题吗?

4

2 回答 2

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

我们决定对 is 进行切片,而不是 .remove,因为 .remove 可能会删除不在 my_word 末尾的匹配项

于 2020-12-18T20:47:53.943 回答
-1

我认为您需要的是一个 for 循环(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)
于 2020-12-18T20:47:01.283 回答