我想计算子字符串“bob”在字符串s中出现的次数。我为edX课程做这个练习。你知道吗
s = 'azcbobobegghakl'
counter = 0
numofiterations = len(s)
position = 0
#loop that goes through the string char by char
for iteration in range(numofiterations):
if s[position] == "b": # search pos. for starting point
if s[position+1:position+2] == "ob": # check if complete
counter += 1
position +=1
print("Number of times bob occurs is: " + str(counter))
但是,s[position+1:position+2]语句似乎工作不正常。我怎么称呼“b”后面的两个字符?你知道吗
不包括第二个切片索引。这意味着
s[position+1:position+2]
是位于position + 1
位置的单个字符,并且这个子字符串不能等于ob
。参见相关的answer。你需要[:position + 3]
:Eric's answer完美地解释了为什么您的方法不起作用(Python中的切片是端部独占的),但是让我提出另一个选项:
或者只是
可以将
.find
与索引一起使用:相关问题 更多 >
编程相关推荐