繁体   English   中英

Pythonendswith() 函数,不带内置函数

[英]Python endswith() function, without the built-in function

我需要在不使用 Python 中的内置函数的情况下创建endswith() 函数。 我想知道是否有什么方法可以让我做得更短更容易? 我确定有,我的方法真的很复杂。

string = "example for endswith"

find = "endswith"

l = len(find)

final = False

b = 0
tstring =[]
new = "" 
for i in string:
    if find[b] == i:
        tstring.insert(b,i)
        b = b + 1
        if b == l:
            print(tstring)
            break
for x in tstring: 
        new += x

print(new)

if(new==find):
    final = True

print(final)

这个怎么样:

def endswith(a, b):
  for i in range(len(b)):
    if a[-1-i] != b[-1-i]:
      return False
  return True

这是一个递归实现,没有用,仅用于教育目的:

def endswith(a, b):
  return not b or (b[-1] == a[-1] and endswith(a[:-1], b[:-1]))

或者,当然,没有循环:

def endswith(a, b):
  return a[-len(b):] == b

但我认为这不是任务的想法。

string = "example for endswith" find = "endswith" l = len(find) final = False print(find[::-1] == string[::-1][:l])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM