在没有内置函数的情况下在 Python 中查找字符串的子字符串

Sec*_*tah 0 python string substring

我正在尝试编写一些代码来查找字符串中的子字符串。到目前为止,我有这个:

main = "dedicated"
sub = "cat"
count = 0
for i in range (0,len(main)):
   match = True
   if sub[0]==main[i]:
     j=0
     for j in range(0,len(sub)):
         if sub[j]!=main[i+j]:
             match = False
             print "No substring"
             break
         else:
             count=count+1
             if match == True and count == len(sub):
                 print "Substring"
                 print "Position start:",i
Run Code Online (Sandbox Code Playgroud)
  • “奉献”和“猫”作品
  • “这是一个例子”和“例子”返回一个 IndexError
  • “无”和“不同”什么都不返回

任何人都可以帮助我/给我指点/改进代码,使其与上面的要点一起正常工作吗?

ins*_*get 6

def index(s, sub):
    start = 0
    end = 0
    while start < len(s):
        if s[start+end] != sub[end]:
            start += 1
            end = 0
            continue
        end += 1
        if end == len(sub):
            return start
    return -1
Run Code Online (Sandbox Code Playgroud)

输出:

>>> index("dedicate", 'cat')
4
>>> index("this is an example", 'example')
11
>>> index('hello world', 'word')
-1
Run Code Online (Sandbox Code Playgroud)