[英]Find last position in Python
I am learning Python and I am trying to resolve this problem without len()
but I am still stuck. 我正在学习Python,我试图解决这个问题没有len()
但我仍然卡住了。 Here is a quiz explanation. 这是一个测验解释。
Define a procedure, find_last, that takes as input two strings, a search string and a target string, and returns the last position in the search string where the target string appears, or -1 if there are no occurrences. 定义一个过程find_last,它将两个字符串,一个搜索字符串和一个目标字符串作为输入,并返回搜索字符串中出现目标字符串的最后一个位置,如果没有出现则返回-1。
Example: find_last('aaaa', 'a') returns 3 示例:find_last('aaaa','a')返回3
Make sure your procedure has a return statement. 确保您的程序有一个return语句。
Here is my code: 这是我的代码:
def find_last(search, target):
target = search.find(target)
while target:
if target == -1:
return target
else:
return target +1
return target
Thank you. 谢谢。
You have several errors to fix: 您有几个错误要修复:
target
is the target string, not the position where you find it. target
是目标字符串,而不是您找到它的位置。 You're overwriting that value. 你正在覆盖这个价值。 search.find
multiple times 您可能需要多次调用search.find
search.find
returns -1. 一旦search.find
返回-1,你就会突破循环。 Your function should then return the previous value returned by search.find
. 然后,您的函数应返回search.find
返回的先前值。 Fixing each of those issues gives you 修复每个问题都可以解决问题
def find_last(search, target):
# Find the first occurrence of target
pos = search.find(target)
# If you found something, keep looking for it until you don't
# find it again
while pos >= 0:
# You found target once; now look for the next occurrence
next_pos = search.find(target, pos + 1)
if next_pos == -1:
# no more targets, so stop looking
break
pos = next_pos
return pos
You could also use return pos
instead of break
. 你也可以使用return pos
而不是break
。
As pointed out in the comments, though, search.rfind(target)
already does what you want. 正如评论中指出的那样, search.rfind(target)
已经做了你想要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.