索引在范围内却触发IndexError?Python初学者求助
提取句子单词首字母时触发IndexError的问题解决
我正在学习Python入门课程,现在碰到个难题:要写程序提取句子里每个单词的首字母。我的思路是遍历字符串的每个字符,检测到空格后输出空格后的下一个字符。程序看起来能运行,但执行if sentence[i] == " ":(第12行)的时候触发了IndexError。我搞不懂为啥,这个错误发生在第一次和第二次输出之间,而且索引好像在字符串范围内。附上我的代码:
sentence = "Humpty Dumpty sat on a wall" #input("Please type in a sentence: ") stop = False i = 0 while i < len(sentence): if stop == False and sentence[i] != " ": print(sentence[i]) i += 1 stop = True else: stop = True while stop == True: if sentence[i] == " ": stop = False i += 1 break else: i += 1
错误原因
问题出在内层while循环没有判断索引是否越界。当程序处理到字符串最后一个单词的首字母后,stop被设为True,进入内层循环。此时代码会一直让i递增,直到找到空格,但原字符串末尾没有空格,i会一直增加到等于len(sentence)(比如原字符串长度是28,i会变成28),而字符串的索引范围是0到len(sentence)-1,这时候访问sentence[i]就会触发IndexError。
修复方案
方案1:修复原代码的索引问题
只需要在内层while循环的条件里加上i < len(sentence),避免索引越界:
sentence = "Humpty Dumpty sat on a wall" #input("Please type in a sentence: ") stop = False i = 0 while i < len(sentence): if stop == False and sentence[i] != " ": print(sentence[i]) i += 1 stop = True else: stop = True # 新增i < len(sentence)的判断,防止索引越界 while stop == True and i < len(sentence): if sentence[i] == " ": stop = False i += 1 break else: i += 1
方案2:用Python更简洁的写法(推荐)
其实Python有更简单的方法处理这个需求,不需要手动遍历索引:
方法A:用split()分割单词
sentence = "Humpty Dumpty sat on a wall" # 按空格分割成单词列表(自动忽略连续空格) words = sentence.split() # 遍历每个单词,取首字母 for word in words: print(word[0]) # 如果要把首字母拼接成字符串输出: # print(''.join(word[0] for word in words))
split()方法默认会把字符串按任意数量的空格分割成单词列表,直接遍历列表取每个单词的第一个字符即可,完全不会有索引问题。
方法B:处理连续空格的遍历写法
如果需要手动处理(比如学习遍历逻辑),可以用标记变量代替索引,避免越界:
sentence = "Humpty Dumpty sat on a wall" first_letters = [] # 标记是否需要记录下一个非空格字符(即单词首字母) need_next = True for char in sentence: if need_next and char != " ": first_letters.append(char) need_next = False # 遇到空格时,标记下一个非空格字符是首字母 elif char == " ": need_next = True print(''.join(first_letters))
这种写法不需要维护索引,通过need_next变量控制何时记录字符,既简单又不会触发索引错误,还能处理多个连续空格的情况。
内容的提问来源于stack exchange,提问作者posypinkshark
相关产品推荐
相关产品推荐

