递归所有子字符串python_使用递归显示字符串中的多个子字符串索引

快速通道

你不必实现你自己的解决方案,它已经完成了!使用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]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值