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

Python中capital_indexes函数无法返回所有大写字母索引的问题咨询

问题分析

你的代码问题出在string.find(i)上:这个方法会返回字符首次出现的索引,而非当前循环中该字符的实际位置。比如在"TEsT"里,最后一个'T'调用find('T')会返回第一个'T'的索引0,而不是正确的3,所以最终输出会是[0,1,0],不符合预期。

解决方法

方法1:用enumerate遍历(最直观)

enumerate可以同时获取字符的索引和值,直接记录符合条件的索引即可:

def capital_indexes(string):
    cap = []
    for idx, char in enumerate(string):
        if char.isupper():
            cap.append(idx)
    return cap

print(capital_indexes("TEsT"))  # 输出: [0, 1, 3]

方法2:列表推导式简化

把上面的逻辑浓缩成一行,更简洁:

def capital_indexes(string):
    return [idx for idx, char in enumerate(string) if char.isupper()]

方法3:用正则表达式(利用你已导入的re模块)

通过re.finditer找到所有大写字母的匹配对象,再提取它们的起始索引:

import re
def capital_indexes(string):
    return [match.start() for match in re.finditer(r'[A-Z]', string)]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 06:30:46