鱼C论坛

 找回密码
 立即注册
查看: 1972|回复: 3

为啥会越界呢

[复制链接]
发表于 2017-9-12 21:14:40 | 显示全部楼层 |阅读模式

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

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

x
就是某节课的课后作业,就是小写字母两边有且仅有三个大写字母,最后能找出来是ilovefishc,
下边有注释的那一行,我想获取字符串的第一个字符和最后一个字符但是我使用str2[0]和str2[8]的时候提示我下标越界,我只好使用切片了str2[:1]和str2[8:],我实在是不知道为啥,求助。
  1. str1 = '...' #很长的字符串我就不上了
  2. password = []
  3. length = 0
  4. for each in str1:
  5.     if each.islower():
  6.         str2 = str1[length - 4 : length + 5]
  7.         count = str2.find('\n')
  8.         if count >= 0:
  9.             str2 = str1[length - 4 : length + count - 4] + str1[length + count - 3: length + 6]
  10.         if str2[:1].islower() and (str2[8:]).islower() and str2[1:4].isupper() and str2[5:8].isupper():################
  11.             password.append(each)
  12.     length+=1
  13. print(password)
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2017-9-12 23:17:41 | 显示全部楼层
说你越界,说明你的str2的长度不够。
str[:1]这是切片,切片不会报错,会给一个[]。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

 楼主| 发表于 2017-9-13 20:04:58 | 显示全部楼层
本帖最后由 宫志强 于 2017-9-13 20:11 编辑
bush牛 发表于 2017-9-12 23:17
说你越界,说明你的str2的长度不够。
str[:1]这是切片,切片不会报错,会给一个[]。


我已经解决了,小问题,开头和结尾没考虑到,开头可能不够9个字符,读取会发生错误
下面是正确代码:
  1. str1 = '...'
  2. password = []
  3. length = 0
  4. for each in str1:
  5.     if length > 3 and length < len(str1) - 5:
  6.         if each.islower():
  7.             str2 = str1[length - 4 : length + 5]
  8.             count = str2.find('\n')
  9.             if count >= 0:
  10.                 str2 = str1[length - 4 : length + count - 4] + str1[length + count - 3: length + 6]
  11.             if str2[0].islower() and (str2[8]).islower() and str2[1:4].isupper() and str2[5:8].isupper():
  12.                 password.append(each)
  13.     length+=1
  14. print(password)
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-9-14 00:00:28 | 显示全部楼层
防止此类问题最好的办法就是倒着取  
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-4-19 14:56

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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