defcount(str, s):
count =0for letter instr:if letter == s:
count = count +1return count
搜索法(find) 的计数方法:不再使用字符串遍历,而是使用上一节中三参数版本的 find 函数;
deffind(word, letter, i):
l =len(letter)
index = i
while index <len(word):if word[index:index+l]== letter:return index
index = index +1return-1defcount(string,str):
count =0
index =0
l =len(str)while index <=len(string):
index = find(string,str, index)if index ==-1:return count
index = index + l
count = count +1print(count('伟大的的祖国伟大的党','伟大'))
defis_reverse(word1, word2):iflen(word1)!=len(word2):returnFalse
i =0
j =len(word2)while j >0:#print(i, j) # 这里添加打印语句if word1[i]!= word2[j]:returnFalse
i = i+1
j = j-1returnTrueprint(is_reverse('pots','stop'))
PS C:\Users\Administrator> python D:\WorkSpace\thinkpython2e\new40.py
Traceback (most recent call last):
File "D:\WorkSpace\thinkpython2e\new40.py", line 17,in<module>print(is_reverse('pots','stop'))
File "D:\WorkSpace\thinkpython2e\new40.py", line 10,in is_reverse
if word1[i]!= word2[j]:
IndexError: string index out of range
为了调试 IndexError: string index out of range 类错误,第一步是在错误出现的行之前,打印索引的值(把前面程序中打印语句前的 # 去除),能获得更多的信息,这里第一次循环打印了索引号0 4,显然索引4超出了 ‘stop’ 索引范围、指定 j 的起始值显然有误,应该为 len(word2)-1,指定正确的索引起始值后,即能解决这个问题;
PS C:\Users\Administrator> python D:\WorkSpace\thinkpython2e\new40.py
04
Traceback (most recent call last):
File "D:\WorkSpace\thinkpython2e\new40.py", line 17,in<module>print(is_reverse('pots','stop'))
File "D:\WorkSpace\thinkpython2e\new40.py", line 10,in is_reverse
if word1[i]!= word2[j]:
IndexError: string index out of range