|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
题:编写一个函数 findstr(),该函数统计一个长度为 2 的子字符串在另一个字符串中出现的次数。
- def findstr(x,y):
- count = 0
- for each in y:
- if each == x[0]:
- index0 = y.index(each)
- if y[index0+1] == x[1]:
- count += 1
- print('The string you want to search for appears',count,'times.',end='')
- x = input('Please input the string you want to search for(length=2):')
- y = input('Please input the string you want to search from:')
- findstr(x,y)
复制代码
这是我的代码,然后我随便检测了一个:
- Please input the string you want to search for(length=2):lo
- Please input the string you want to search from:love is a long travel
- The string you want to search for appears 3 times.
复制代码
我怎么看也是两次而不是三次呀,但是就是不知道代码错哪了,因为有的例子做出来是对的。求大佬解答!!
(忽略塑料英语)
你用 index,查找字符串,而 index 每次查找字符串都是将从左到右第一次遇到的字符串索引值返回
所以这里你每次循环 index0 的值都为固定值,而当你 for each in y 循环到最后时,即最后的字符 'l' 时,因为 index0 始终为第一个遇到字符的索引值,则始终返回 0
所以 if y[0+1] == x[1]: 又恰好导致条件成立所以把最后的 l 也计算入查找到的次数中了
你可以用个临时变量来记录索引值,或者像甲鱼哥答案 for 循环 range 字符长度,直接循环索引值,且调用 find 函数,配合切片达到目的
两者皆可,这里不用 index 是因为 index 若没有查找到,会导致程序报错,所以用 find ,若没查找到会返回 -1
临时变量的参考代码:
- def findstr(x,y):
- count = 0
- index_ = 0
- for each in y:
- index_ += 1
- if each == x[0]:
- if y[index_:index_+1] == x[1]:
- count += 1
- print('The string you want to search for appears',count,'times.',end='')
- x = input('Please input the string you want to search for(length=2):')
- y = input('Please input the string you want to search from:')
- findstr(x,y)
复制代码
|
|