快速通道
你不必实现你自己的解决方案,它已经完成了!使用re模块中的finditer函数:>>> import re
>>> s = 'your code works with wrongly correlated coefficients which incorporates more costs'
>>> matches = re.finditer('co', s)
>>> positions = [ match.start() for match in matches ]
>>> positions
[5, 29, 40, 61, 77]
你自己的方式
如果您想实现自己的实现(使用递归),可以利用str.find函数的额外参数。让我们看看help(str.find)对此有何看法:
^{pr2}$
还有一个名为start的额外参数,它告诉str.find从哪里开始搜索子字符串。这正是我们需要的!在
因此,修改您的实现,我们可以得到一个简单、快速和漂亮的解决方案:def substring_match_exact(pattern, string, where_should_I_start=0):
# Save the result in a variable to avoid doing the same thing twice
pos = string.find(pattern, where_should_I_start)
if pos == -1:
# Not found!
return []
# No need for an else statement
return [pos] + substring_match_exact(pattern, string, pos + len(key))
递归在这里做什么?在首先搜索字符串中从位置0开始的子字符串。在
如果找不到子字符串,则返回一个空列表[]。在
如果找到了子字符串,它将返回[pos],加上该子字符串将出现在字符串中的所有位置,起始位置是pos + len(key)。在
使用我们全新的功能>>> s = 'your code works with wrongly correlated coefficients which incorporates more costs'
>>> substring_match_exact('co', s)
[5, 29, 40, 61, 77]