I'm trying to code a function to find the last substring in a string. I don't want a solution in any other code, I need to do it using my own procedure for course homework.
Most tests work, although when testing aa in aaaaa it fails. I understand why because its starting from a position with only a left, but how can I fix this?
def find_last(s, c):
last_position = 0
result = -1
while True:
next_position = s.find(c, last_position)
if next_position == -1:
break
result = next_position
last_position = next_position + len(c)
return result
print(find_last("aaaaa", "aa")) # should output 3 but doesn't?
aaaaastring from the end. Think: indexing by length of the string, then slowly building the substring from the end and checking along the way. ;)aaaaawont always be the same, it needs to work for any string. I think @JeromeMontino also thought it was only foraaaaanot sure.aaaaa. If you don't want to use built-in methods, you can either reverse as Raman pointed out and check from the reversed version OR you work backwards the string's index using its length as initial index and decrementing and checking along the way.str.findand replace it with string slicing and comparison.