czh1303541051 发表于 2020-4-16 20:11:02

for遍历问题

2. 编写一个函数 findstr(),该函数统计一个长度为 2 的子字符串在另一个字符串中出现的次数。例如:假定输入的字符串为“You cannot improve your past, but you can improve your future. Once time is wasted, life is wasted.”,子字符串为“im”,函数执行后打印“子字母串在目标字符串中共出现 3 次”。

def findStr(desStr, subStr):
    count = 0
    length = len(desStr)
    if subStr not in desStr:
      print('在目标字符串中未找到字符串!')
    else:
      for each1 in range(length-1):      
            if desStr == subStr:
                if desStr == subStr:
                  count += 1
                  
      print('子字符串在目标字符串中共出现 %d 次' % count)

desStr = input('请输入目标字符串:')
subStr = input('请输入子字符串(两个字符):')
findStr(desStr, subStr)


里头这个for遍历的到底是什么,我觉得是desStr字符串的长度,但是这个函数却能实现出结果

zltzlt 发表于 2020-4-16 20:13:52

就是 desStr 长度再 -1,因为要对 desStr 进行判断

czh1303541051 发表于 2020-4-16 20:42:07

zltzlt 发表于 2020-4-16 20:13
就是 desStr 长度再 -1,因为要对 desStr 进行判断

你这种绝对语气让我突然看懂了   我之前一直以为是字符串现在再看原来是数值
页: [1]
查看完整版本: for遍历问题