Python 3.x:使用endswith()查找子字符串是否在字符串的末尾

时间:2017-07-21 05:33:17

标签: python string

我创建了一个程序来检查字符串是否是另一个字符串的子字符串,并且该子字符串的附加条件在最后。

def atEnd(first, second):
    if second in first and first.endswith(second):
        return True
    else:
        return False
first, second = input('Enter two strings: ').split()
print(atEnd(first, second))

有没有办法在不使用.endswith()函数的情况下找到相同的结果?

3 个答案:

答案 0 :(得分:2)

first[-len(second):] == second

将完成这项工作。

答案 1 :(得分:2)

您的atEnd函数与str.endswith完全冗余,print(first.endswith(second))是一种内置的本机方法,因此已经具有高效的实现。

我只想写str.endswith - 没有必要进一步复杂化。

如果由于某种原因你真的想要一个免费的功能而不是一个方法,那么你可以直接调用print(str.endswith(first, second))endswith

如果您出于效率原因想编写自己的实现,那么使用替代算法(例如构建后缀树)可能会更好。如果你想编写自己的实现来理解低级字符串操作,你真的应该学习C并阅读the CPython implementation source code。如果你这样做是因为学校作业告诉你不要使用Dim ClassFolder As String = Path.Combine(My.Application.Info.DirectoryPath, "SaveToFolder\") Dim ClassTemplate As String = My.Application.Info.DirectoryPath & "\Templates\TemplateFile.xlsx" 那么这对我来说似乎是一个愚蠢的任务 - 你应该向老师询问更多信息。

答案 2 :(得分:0)

尝试使用re模块的方法findall

import re   

EndsWith = lambda first,second: re.findall("("+first+")$",second) != []