python:在字符串中查找子字符串

时间:2014-06-21 14:37:03

标签: python

我试图编写一个程序来计算子字符串在字符串中出现的次数。

word = "wejmfoiwstreetstreetskkjoih"
streets = "streets"
count = 0

if streets in word:
    count += 1

print(count)

你可以看到"街道"出现两次,但最后的街道也是街道的开始。我无法想出一种循环的方法。

谢谢!

3 个答案:

答案 0 :(得分:4)

可以使用正则表达式

完成
>>> import re
>>> text = 'streetstreets'
>>> len(re.findall('(?=streets)', text))
2

来自the docs

  

(?= ...)

     

匹配if ...匹配next,但不消耗任何   串。这称为先行断言。例如,艾萨克   (?= Asimov)只有在跟随'Asimov'之后才会匹配'Isaac'。

答案 1 :(得分:2)

又快又脏:

>>> word = "wejmfoiwstreetstreetskkjoih"
>>> streets = "streets"
>>> sum(word[start:].startswith(streets) for start in range(len(word)))
2

答案 2 :(得分:0)

通用(虽然不那么优雅)的方式是这样的循环:

def count_substrings(stack, needle):
    idx = 0
    count = 0
    while True:
        idx = stack.find(needle, idx) + 1 # next time look after this idx
        if idx <= 0:
            break
        count += 1
    return count

我的测量显示,它比每个子字符串startswith的解决方案快〜8.5倍。

相关问题