-1

I need to make the endswith() function without using the built-in function in Python. I wanted to know if there is any way i could do it shorter and easier? I'm sure there is, my way is really complicated.

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)
double-beep
  • 5,031
  • 17
  • 33
  • 41
Vida
  • 11
  • 1
  • 1
    please include your code on this site (there is a formating option: {}) and don't link to external sites – Florian H Mar 29 '19 at 15:11
  • 1
    Please include your code and all relevant information as **text** in your question, not as images. – Thierry Lathuille Mar 29 '19 at 15:12
  • Welcome to StackOverflow, please complete your [tour] and see [ask], and [edit] your question with your codes directly within the question body. – r.ook Mar 29 '19 at 15:12
  • 2
    Sentences like "It works, but i need a shorter and better one." are an indicator that your question would probably be better suited for codereview.stackexchange.com ;> – meissner_ Mar 29 '19 at 15:15
  • I'm new to the site sorry, there i edited it. – Vida Mar 29 '19 at 15:16
  • So my code works, but i was wondering if there is any easier and more simple way of doing it, which i am sure there is. – Vida Mar 29 '19 at 15:17

2 Answers2

0

How about this one:

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

Here's a recursive implementation, not useful, just for educational purposes:

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

Or, of course, without a loop:

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

But I think that wasn't the idea of the task.

Alfe
  • 56,346
  • 20
  • 107
  • 159
  • Thank you very much for the help! :) – Vida Mar 29 '19 at 15:24
  • 1
    Welcome to StackOverflow! There's no need to leave thank-you comments. Just upvote an answer when it helped you (upwards triangle left of the answer, that's the simpler equivalent of a thank-you) and/or accept it (checkmark) if it solves your problem. – Alfe Mar 29 '19 at 15:25
0
string = "example for endswith"

find = "endswith"

l = len(find)

final = False

print(find[::-1] == string[::-1][:l])
Saya
  • 323
  • 2
  • 6
  • I recommend not using variables names `l`, `O` or `I`. depending on the font they look a lot like `1`, `0` and `l` and can lead to a lot of confusion. – Alfe Mar 29 '19 at 16:32
  • I second Alfe's comment. Generally speaking, try not to use single letter variable names – blueberryfields Mar 29 '19 at 18:29
  • Please describe, what did you change and why, to help others understand the problem and this answer – FZs Mar 29 '19 at 18:54