首页 > 解决方案 > 如果子字符串位于单词的末尾,则手动字符串“in”函数不起作用

问题描述

我正在尝试为in分配手动编写 python 字符串函数。使用此代码,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'and t = 'py')。如果我在 末尾添加任意字符s,它就可以工作。为什么是这样?

标签: pythonpython-3.xstringsubstringmanual

解决方案


也许?

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)

推荐阅读