如果子字符串位于单词

时间:2019-09-29 23:45:53

标签: python python-3.x string substring manual

我正在尝试手动为作业分配python字符串in函数。使用此代码,其中s是字符串,而t是我要查找的子字符串:

def test(s, t):
    stidx = 0
    while stidx < len(s):
        idx = 0
        for i in s[stidx:]:
            if idx < len(t):
                if t[idx] == i:
                    idx += 1
                    continue
                else:
                    break
            if idx == len(t):
                return True
        stidx += 1
    return False

上面的代码有效,但当我在单词的末尾检查子字符串时(例如s = 'happy't = 'py')。如果我在s的末尾添加一个任意字符,它将起作用。为什么是这样?

1 个答案:

答案 0 :(得分:0)

也许吗?

def test(s, t):
    """
    :param s:   exp: happy
    :param t:   exp: py
    :return:
    """
    tmp = result = 0
    t_len = len(t)
    while tmp <= len(s)-t_len:
        if s[tmp: tmp+t_len] == t:
            result = 1
            break
        else:
            tmp += 1
            continue

    return bool(result)