酒醉三分醒 发表于 2020-2-23 12:05:11

【Python入门】18讲动动手2

要求编写一个函数来统计一个长度为 2 的子字符串在另一个字符串中出现的次数。
想了好久感觉还是有点混乱,想请教大神们几个问题:
1.答案给的是:
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)    #为什么要格式化count而不是直接打印?

desStr = input('请输入目标字符串:')
subStr = input('请输入子字符串(两个字符):')
findStr(desStr, subStr)
2..统计字数可以用如果输入字符串的长度不为2,要怎么补充代码,引导操作者重新输入直到长度为2时再执行次数统计?
3.我写的程序怎么修改
def findstr(longstr,str2):
    length = len(str2)

    if length != 2:
      str2 = print('该子字符串长度不符,请重新输入(两个字符):')   #我想让操作者重新输入后直到字符串长度为2再执行,但是这里不知道该怎么改
    else:
      if str2 not in longstr:
            print('在目标字符串中未找到字符串!')
      else:
            count = longstr.count(str2)         #不用答案的方法,直接用这个BIF来统计可以吗?

            print('子字符串在目标字符串中共出现',count,'次')

longstr = input('请输入目标字符串:')
str2 = input('请输入子字符串(两个字符):')

jackz007 发表于 2020-2-23 12:41:29

本帖最后由 jackz007 于 2020-2-23 13:00 编辑

      用现成的 BIF 应该是不符合题目要求。
      楼主试试这个代码
#-*-coding:gbk-*-

def findstr(longstr , str2):
    c= sum( == str2])
    return c + sum( == str2])

f1 , f2 = False , False
while not f1 or not f2:
    if not f1:
      longstr = input('请输入目标字符串:') . strip()
      if len(longstr) > 1:
            f1 = True
      else:
            if len(longstr) == 0:
                break
            else:
                print('目标字符串的长度必须大于 1!\n')
    if f1 and not f2:
      str2 = input('请输入子字符串(两个字符):') . strip()
      if len(str2) == 2:
            f2 = True
      else:
            if len(str2) == 0:
                break
            else:
                print('字符串必须是两个字符!\n')
    if f1 and f2:
      count = findstr(longstr , str2)
      if count > 0:
            print('子字符串在目标字符串中共出现' , count , '次')
      else:
            print('在目标字符串中未找到字符串!')
      运行实况:
C:\Bin>python x2.py
请输入目标字符串:I love you , Do you love me?
请输入子字符串(两个字符):ov
子字符串在目标字符串中共出现 2 次

C:\Bin>
页: [1]
查看完整版本: 【Python入门】18讲动动手2