【发布时间】:2012-05-10 15:31:23
【问题描述】:
为了更好地理解它,我正在玩弄一个任务函数。它旨在查找字符串中子字符串的最后一次出现。该函数应该返回子字符串最后一次出现的开始位置,或者如果根本没有找到子字符串,它必须返回 -1。 “标准”方式如下:
def find_last(full, sub):
start = -1
while True:
new = full.find(sub, start + 1)
if new == -1:
break
else:
start = new
return start
我想尝试让它反向搜索,因为这似乎是更有效的方式。所以我尝试了这个:
def find_last(full, sub):
start = -1
while True:
new = full.find(sub, start)
if new == -1 and abs(start) <= len(full): #evals to False when beginning of string is reached
start -= 1
else:
break
return new
我们得到了一些需要通过的测试用例,而我的反向函数只通过了一个:
print find_last('aaaa', 'a')
>>>3
print find_last('aaaaa', 'aa')
>>>3
print find_last('aaaa', 'b')
>>>-1
print find_last("111111111", "1")
>>>8
print find_last("222222222", "")
>>>8 #should be 9
print find_last("", "3")
>>>-1
print find_last("", "")
>>>0
有人能解释一下为什么 find 在负索引的情况下会这样吗?还是只是我的代码中的一些明显错误?
【问题讨论】:
-
我知道这是家庭作业,但很高兴知道真正的代码会为此使用 .rfind() 方法。
-
@yak wow,那会更重要,谢谢。