python - 使用 .endswith(tuple) 测试时获取实际结尾

标签 python

我发现了一个很好的问题,可以使用以下方法搜索字符串的多个结尾: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/

相关文章:

python - Epochs Vs Pass Vs Iteration

python - MongoDB 插入速度权衡

python - 从动词列表中检索动词

python - 将列 reshape 为数据框 Pandas 中的行

c# - 缺少成员异常 : 'Guid' object has no attribute 'length'

python - 在 Python 中释放内存

python - 传递列表中第一个更改的值

python - 删除市场数据中的重复项

Python Flask Docker 迁移

带有事件的 Python TAPI COM 对象