【发布时间】:2015-12-05 23:41:24
【问题描述】:
搜索了这个,但所有答案都超出了我的范围,因为我还在学习。我正在尝试查找字符串中某个单词的出现次数。我想出了以下代码,但不断得到奇怪的答案。
s = 'bobzbobz'
word = 'bob'
index = 0
instance = []
while index < len(s):
instance.append(s.find(word,index))
index += 1
print len(instance) #instance = [0, 4, 4, 4, 4, -1, -1, -1]???? Why??
这应该打印 2,但我得到 8。原因是因为我的实例列表中有很多重复值。
【问题讨论】:
-
如果这就是你想要的,
s.count(word)会为你做的:-) -
添加 -1 是因为当未找到子字符串时 find 返回 -1,您会不断获得 4,因为您只将索引移动一个位置就一直在寻找最后一个 bob
-
要查看您的代码出了什么问题,请考虑当
index为 1 时会发生什么... -
@alexis,计数对重叠字符串不起作用