我发现了一个很好的问题,可以使用以下方法搜索字符串的多个结尾:endswith(tuple)
Check if string ends with one of the strings from a list
我的问题是,如何返回元组中实际发现匹配的值?如果我有多个匹配项,如何选择最佳匹配项?
例如:
str= "ERTYHGFYUUHGFREDFYAAAAAAAAAA"
endings = ('AAAAA', 'AAAAAA', 'AAAAAAA', 'AAAAAAAA', 'AAAAAAAAA')
str.endswith(endings) ## this will return true for all of values inside the tuple, but how can I get which one matches the best
在这种情况下,可以从元组中找到多个匹配项,我该如何处理这个问题并仅返回最佳(最大)匹配项,在本例中应该是:'AAAAAAAAA'
我想在末尾删除(可以使用正则表达式等来完成)。
我的意思是可以在 for 循环中执行此操作,但也许有一种更简单的 Python 方式?
最佳答案
>>> s = "ERTYHGFYUUHGFREDFYAAAAAAAAAA"
>>> endings = ['AAAAA', 'AAAAAA', 'AAAAAAA', 'AAAAAAAA', 'AAAAAAAAA']
>>> max([i for i in endings if s.endswith(i)],key=len)
'AAAAAAAAA'
关于python - 使用 .endswith(tuple) 测试时获取实际结尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32349928/