You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决统计第二个字符为'a'的单词时的string index out of range错误?

解决方案

问题出在短单词(比如示例里的"a")长度不足2,直接访问索引1会触发IndexError。解决思路是先判断单词长度至少为2,再检查第二个字符是否为'a'。

完整代码实现

input_str = "banana in a bag"
words = input_str.split()
matched_words = []

for word in words:
    # 先确保单词长度足够,再检查第二个字符
    if len(word) >= 2 and word[1] == 'a':
        matched_words.append(word)

# 输出结果
print(' '.join(matched_words))

代码说明

  • input_str.split():将输入字符串按空格分割成单词列表。
  • len(word) >= 2:过滤掉长度小于2的单词,避免索引越界错误。
  • word[1] == 'a':检查单词的第二个字符(Python中字符串索引从0开始)是否为'a'。
  • ' '.join(matched_words):将符合条件的单词用空格连接成字符串输出,匹配示例的期望格式。

运行这段代码,输入banana in a bag会输出banana bag,且不会出现索引越界错误。

内容的提问来源于stack exchange,提问作者Sai Sree

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 00:20:29