字符串中出现子串的次数(打印类型错误时出错)

时间:2017-09-22 18:09:01

标签: python

s = 'azcbobobegghakl'

count = 0
for i in range(len(s)-2):
   count += s[i]=='b' and s[i+1]=='o' and s[i+2]=='b'

print(f'Number of times bob occurs is: {count}')

例如这应该正常吗?当我在命令行中键入count时,它给出了2,这是正确的答案,但print语句返回

TypeError: 'int' object is not callable

我尝试过不同版本的打印,例如

print('Number of times bob occurs is: ' + str(count))

print('Number of times bob occurs is: ' + int(count))

但他们都给我错误,我知道这是非常基本但我正在努力尝试谷歌,大多数东西都比它需要的更复杂。

编辑:解决了,我重新启动了IDE,它开始工作,抱歉浪费了每个人的时间。

1 个答案:

答案 0 :(得分:-1)

这将是更好的通用解决方案:

s = 'azcbobobegghakl'

find_str = "bob"

_i = 0
_count = 0
while _i <= len(s):
    if s[_i:_i+len(find_str)] == find_str:
            _count += 1
    _i += 1

print("Number of times {} occurs is: {}".format(find_str, _count))

它工作正常,但不是正确的方法。如果你有更长的刺痛怎么办?

s = 'azcbobobegghakl'

count = 0
for i in range(len(s)-2):
    count += s[i]=='b' and s[i+1]=='o' and s[i+2]=='b'

print('Number of times bob occurs is: {}'.format(count))
# Number of times bob occurs is: 2