鱼C论坛

 找回密码
 立即注册
查看: 2661|回复: 4

18讲 findstr() 求解

[复制链接]
发表于 2015-3-16 10:25:38 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 戴宇轩 于 2015-3-20 16:48 编辑

18讲作业 第2题动动手
编写一个函数 findstr(),该函数统计一个长度为 2 的子字符串在另一个字符串中出现的次数。例如:假定输入的字符串为“You cannot improve your past, but you can improve your future. Once time is wasted, life is wasted.”,子字符串为“im”,函数执行后打印“子字母串在目标字符串中共出现 3 次”。
为什么我这样写 会out of index 报错
  1. def findstr(words='',key=''):
  2.         length=len(words)
  3.         times=0
  4.         i=0
  5.         while i<length:
  6.                 if words[i]+words[i+1]==key[0]+key[1]:
  7.                         times +=1
  8.                 i+=1
  9.         return times
复制代码
而我切片写就可以通过
  1. def findstr(words='',key=''):
  2.         length=len(words)
  3.         times=0
  4.         i=0
  5.         while i<length:
  6.                 if words[i:i+2]==key:
  7.                         times +=1
  8.                 i+=1
  9.         return times
复制代码
[/i]
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2015-3-16 12:40:50 | 显示全部楼层
  1. while i<length - 1:
复制代码

小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2015-3-16 17:00:14 | 显示全部楼层
:shock: 我是问,为什么用切片不会越界 用 index 会越界:lol:
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2015-3-16 20:39:29 | 显示全部楼层
切片不会越界
>>> s = 'test'
>>> s[:100]
'test'
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2015-3-17 21:48:36 | 显示全部楼层
字符串的index是从0开始的,按照你的程序,当你的i检查到length-1的时候,执行下面的代码words[i+1]中的i+1是越界的,因为字符串索引是从0到length-1
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2026-2-15 06:01

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表