|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
编写一个函数 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): ## ----------请问这个为什么是length-1,用length就不行???
if desStr[each1] == subStr[0]:
if desStr[each1+1] == subStr[1]:
count += 1
print('子字符串在目标字符串中共出现 %d 次' % count)
desStr = input('请输入目标字符串:')
subStr = input('请输入子字符串(两个字符):')
findStr(desStr, subStr)
本帖最后由 jackz007 于 2020-11-10 16:44 编辑
for each1 in range(length-1): ## ----------请问这个为什么是length-1,用length就不行???
if desStr[each1] == subStr[0]:
if desStr[each1]+1] == subStr[1]:
是因为红色的标注的地方,如果不用 length-1 当 each1 == length - 1 的时候,each + 1 = length,作为下标就已经越界了。
|
|