def findLast(filename,key):
infile = open(filename,"r")
outfile = open("result.txt","w")
text = infile.read()
position = text.find(key)
if position == -1:
outfile.write(key + " is not found.\n")
else:
outfile.write(key + " is at " + str(position) + ".\n")
outfile.close()
infile.close()
print("Done")
The above function is a function that finds only the first string. How can we create a function that uses the while function to find only the last string? <
find python
>>> help('s'.find)
Help on built-in function find:
find(...) method of builtins.str instance
S.find(sub[, start[, end]]) -> int
Return the lowest index in S where substring sub is found,
such that sub is contained within S[start:end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
>>> text = 'ab ab cd ab cd ab ab ac ab af'
>>> text.find('ab')
0
>>> text.find('ab', 1)
3
>>> text.find('ab', 4)
9
>>> text.find('ab', 10)
15
>>> text.find('ab', 16)
18
>>> text.find('ab', 19)
24
>>> text.find('ab', 25)
-1
>>> text[24:]
'ab af'
The find
method can give you an index to start the search. So, if the search is successful, if you repeat the cycle of the starting index to a value greater than the found index, until you return -1, the index before -1 will be the last match. Repeat this in the while
loop.
def find_last(text, key):
start_index = 0
last_found_index = -1
while True:
i = text.find(key, start_index)
if i == -1:
break
last_found_index = i
start_index = i+1
return last_found_index
To do a better job, I think there is also a way to search binary using the end
factor of find
.
© 2024 OneMinuteCode. All rights reserved.