如何使用python

时间:2016-06-12 08:38:24

标签: python python-2.7

我正在尝试查找“abb”的字符串出现次数,例如'abdebobdfhbobob'。

我的代码(我通过另一个stackoverflow问题找到)是:

s = 'abdebobdfhbobob'  
print 'The number of times bob occurs is: ' + str(s.count('bob'))

此代码打印出来: bob发生的次数是:2 ,这对我需要的不正确,因为答案应为3。

问题在于,此代码不会将'abdebobdfh bobob '视为两个不同的bob,这就是我想要的。

如何修复代码以将字符串的bobob部分计为两个单独的bob?

4 个答案:

答案 0 :(得分:6)

基于documentationstr.count()返回[start, end]范围内子字符sub的非重叠出现次数。您可以使用基于positive lookahead的正则表达式来查找重叠的字符串:

>>> import re
>>> s = 'abdebobdfhbobob'
>>> len(re.findall(r'(?=bob)', s))
3

如果你不想使用正则表达式,你可以在sum()函数中使用一个生成器表达式,它将遍历长度为3的所有子字符串,并计算等于'bob的那些子字符串的数量“:

>>> sum(s[i:i+3] == 'bob' for i in range(len(s)-2))
3

答案 1 :(得分:0)

如果您不想使用正则表达式,可以使用zip从字符串创建所有三元组,然后使用list.count

>>> word = 'bob'
>>> triplets = (''.join(k) for k in zip(*[s[i:] for i in range(len(word))]))
>>> triplets.count(word)
3

通过压缩这些字符串来创建三元组:

     ▼     ▼ ▼
'abdebobdfhbobob'
'bdebobdfhbobob'
'debobdfhbobob'
     ▲     ▲ ▲

如果你不介意使用元组:

>>> word = 'bob'
>>> triplets = zip(*[s[i:] for i in range(len(word))])
>>> triplets.count(tuple(word))
3

提示:如果您还要计算其他字数,请使用collections.Counter

答案 2 :(得分:0)

我们可以检查所有可能的候选人:

def count_substrings(sub, main):
    n = len(sub)
    return sum(sub == main[i : i+n] for i in range(len(main) - n + 1))

s = 'abdebobdfhbobob'
sub = 'bob'
print('The number of times %s occurs is: %d' % (sub, count_substrings(sub, s)))  # 3

答案 3 :(得分:0)

为什么不轻松一点?

bobc=0
for i in range (0,len(s)-2):
    if s[i:i+3]=='bob':
        bobc+=1
        i=+1
print('Number of bob:'+str(bobc))
相关问题