小甲鱼python第18讲课后习题的操作题第二题有点疑问
编写一个函数 findstr(),该函数统计一个长度为 2 的子字符串在另一个字符串中出现的次数。例如:假定输入的字符串为“You cannot improve your past, but you can improve your future. Once time is wasted, life is wasted.”,子字符串为“im”,函数执行后打印“子字母串在目标字符串中共出现 3 次”。def findstr(string,str_son):
times = 0
for each in string:
if str_son == each:
i = string.find(each) #用find方法返回这个元素的索引值
if str_son == string:
times += 1
print('子字符串在目标字符串中共出现' , times , '次')
return times
string = input('请输入目标字符串:')
str_son = input('请输入子字符串(两个字符):')
findstr(string,str_son)
问题:为啥我这个方法最后返回的是6次啊?请各位大佬赐教 本帖最后由 疾风怪盗 于 2020-9-9 23:41 编辑
i = string.find(each)# 用find方法返回这个元素的索引值
这一步有问题,一直找到的是第11位的数,没变化
输出是6,意思找到了6个i,就没判断m 这样写就行了
def findstr(string, str_son):
times = 0
while string.find(str_son)>0:
num=string.find(str_son)
print(f'子字符串在目标字符串中:第{num}位')
times=times+1
string=string
print(f'剩余要找的字符串为:{string}')
print(f'子字符串在目标字符串中共出现{times}次')
return times
#string = input('请输入目标字符串:')
string ='You cannot improve your past, but you can improve your future. Once time is wasted, life is wasted.'
#str_son = input('请输入子字符串(两个字符):')
str_son ='im'
findstr(string, str_son) def findstr(string, str_son):
return len(string.split(str_son)) - 1
string ='You cannot improve your past, but you can improve your future. Once time is wasted, life is wasted.'
str_son ='im'
print(findstr(string, str_son))
页:
[1]