【发布时间】:2020-07-30 09:32:33
【问题描述】:
返回字符串“code”出现在给定字符串中的任何位置的次数,除了我们将接受任何字母作为“d”,因此“cope”和“cooe”计数。
count_code('aaacodebbb') → 1
count_code('codexxcode') → 2
count_code('cozexxcope') → 2
我的代码
def count_code(str):
count=0
for n in range(len(str)):
if str[n:n+2]=='co' and str[n+3]=='e':
count+=1
return count
我知道正确的代码(只需在第 3 行添加 len(str)-3 即可)但我无法理解为什么 str[n:n+2] 没有'-3' 和 str[n+3] 也能工作
有人可以解决我对此的疑问吗?
【问题讨论】:
-
切片和单项索引对超出范围的索引的工作方式有所不同。
str[n+3:n+4]可以在这里工作。
标签: python python-3.x