import re
st=input() #The input string
ss=input() #The substring to be searched
lss=len(ss)
lst=len(st)
x=lst-lss
for i in range(x):
r=re.search(r'(%s)'%ss,st,i)
if r:
print(r.start(),r.end())
上面的代码是对任务的响应。任务是:
给出了一个字符串S。你知道吗
我需要找到S中字符串k的开始和结束的索引
如果输入为:
aaadaa
aa
输出应为:
(0, 1)
(1, 2)
(4, 5)
我知道我写的代码是错误的,因为我没有得到想要的输出。我无法说服自己这是错的,我只想知道为什么for循环后的代码不起作用? 有人能帮我渡过难关吗?你知道吗
您应该首先查看^{} 的文档,它的第三个参数是
flag
。你知道吗在您的例子中,您正在寻找重叠的结果,我意识到没有直接的解决方案,所以我编写了一个递归
谁的输出是
它应该像你期望的那样工作。你知道吗
我检查了已有的解决方案,它们不符合您的要求:
re.finditer
只能进行非重叠的搜索。你知道吗re.findall
执行重叠搜索,但检索索引失败。你知道吗re.finditer
和带有look ahead的re.findall
只返回匹配的文本。你知道吗我想写这个函数是最好的方法。你知道吗
问得好。你知道吗
相关问题 更多 >
编程相关推荐