python - 如果子字符串位于单词的末尾,则手动字符串“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
,它就可以工作。为什么是这样?
解决方案
也许?
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)
推荐阅读
- javascript - 无法导入反应类型
- c++ - 在 C++/oscpack 中为激光雷达构建带有 for 循环的 OSC 消息
- python - 我在使用 selenium 通过 xpath 按下按钮时遇到问题
- php - 是否可以从 cakePHP 中非常长的文本列中获取有限数量的字符串
- nginx - 使用 NGINX 的私有 Azure 负载均衡器返回 400 响应
- redis - Redis,几乎没有命令正常工作,为 KNOWN COMMANDS 获取错误未知命令
- javascript - 多个输入的重复输入值
- python - 在没有命令的情况下触发 ConversationHandler?
- r - r - 使用 group_by 和 mutate 根据多个条件添加新列时出现意外的“=”
- dialog - 返回“另存为”对话框 powerbuilder