我创建了一个程序来检查字符串是否是另一个字符串的子字符串,并且该子字符串的附加条件在最后。
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()函数的情况下找到相同的结果?
答案 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) != []