查找空字符串的方法 [英] Find method with empty string

查看:44
本文介绍了查找空字符串的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了更好地理解它,我正在玩一个用于任务的函数.它旨在查找字符串中子字符串的最后一次出现.该函数应返回子字符串最后一次出现的开始位置,或者如果根本找不到子字符串,则必须返回 -1.标准"方式如下:

I was playing around with a function for an assignment just to better understand it. It was meant to find the last occurrence of a sub-string within a string. The function should return the position of the start of the last occurrence of the sub-string or it must return -1 if the sub-string is not found at all. The 'standard' way was as follows:

def find_last(full, sub):
    start = -1
    while True:
        new = full.find(sub, start + 1)
        if new == -1:
            break
        else:
            start = new
    return start

我想尝试让它反向搜索,因为这似乎是更有效的方式.所以我尝试了这个:

I wanted to try and have it search in reverse, as this seemed to be the more efficient way. So I tried this:

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

我们得到了一些需要通过的测试用例,而我的反向函数除了一个之外都通过了:

We were given a handful of test cases which needed to be passed and my reversed function passed all but one:

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 在负索引时会出现这种情况吗?或者只是我的代码中有一些明显的错误?

Can someone kindly explain why find is behaving this way with negative indexing? Or is it just some glaring mistake in my code?

推荐答案

空字符串可以在任何位置找到.用 -1 初始化 start 会让你的算法从倒数第二个位置开始搜索,而不是最后一个.

The empty string can be found at any position. Initializing start with -1 makes your algorithm beginning its search at the penultimate position, not the last.

最后一个位置是在字符串的最后一个字符之后,但是您开始查看字符串的最后一个字符.

The last position is after the last character of the string, but you are starting to look at the last character of the string.

这篇关于查找空字符串的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆