python - Python - 在字符串中查找子字符串并记录元组中子字符串的位置
问题描述
检查此功能时出现以下错误。我非常接近,但不明白为什么循环在到达文本末尾后继续。如何让它在到达要搜索的字符串末尾后停止搜索子字符串?
错误:调用 findall('how now brown cow', 'ow') 返回 (1, 5, 10, 15, -1, 1, 5, 10, 15, -1, 1, 5, 10, 15, - 1, 1, 5),而不是 (1, 5, 10, 15)。
注意 - 我已经在堆栈溢出中搜索了类似的问题,但没有看到任何可以帮助我使用我迄今为止准备的方法解决这个问题的东西。请指教。非常感谢这个新手!!:)
def findall(text,sub):
"""
Returns the tuple of all positions of substring sub in text.
If sub does not appears anywhere in text, this function returns the
empty tuple ().
Examples:
findall('how now brown cow','ow') returns (1, 5, 10, 15)
findall('how now brown cow','cat') returns ()
findall('jeeepeeer','ee') returns (1,2,5,6)
Parameter text: The text to search
Precondition: text is a string
Parameter sub: The substring to search for
Precondition: sub is a nonempty string
"""
result = ()
x = 0
pos = 0
for x in range(len(text)):
if sub in text:
# find pos of sub in text starting from pos in text
pos = introcs.find_str(text,sub,pos)
# record result
result = result + (pos,)
# increase accumulator by 1 to find next pos of sub in text
pos = pos + 1
else:
# when sub is not present in text
result = ()
return result
解决方案
使用递归
def findall(text,sub,list1=[],l=0):
try:
a = text.index(sub)
except:
return list1
list1.append(a+l)
l+=1+a
return findall(text[a+1:], sub, list1,l)
text = 'aascfvbscaaasc'
sub = 'a'
b=findall(text,sub)
print(text)
print(b)
# [0, 1, 9, 10, 11]
推荐阅读
- axapta - Dynamics Axe 如何将过滤器添加到网格
- flutter - 颤振:如何从数据库中获取数据并在整个应用程序中使用它
- javascript - “Uncaught SyntaxError: Unable to parse bindings”关于一行 if 条件
- sql - 获取没有特定日期的两个日期之间的差异天数
- math - 计算第 n 个范围后的 IP
- html - img 标签未读取在 src reactJS 中传递的 url
- java - 调用带参数和不带参数的函数有什么区别?
- python - 将 pyinstaller 与 --noconsole --onefile 一起使用时 subprocess.run 不起作用
- c# - Visual Studio 2019 IIS 配置文件创建破坏 Azure 应用服务的 web.config 文件
- json - 将 api 响应转换为 pandas