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

如何在Python中查找字符串中重复字符的下一个索引?

在Python中查找字符串里重复字符的所有索引

str.index()方法默认只会返回目标字符第一次出现的索引,要获取后续重复字符的索引,你可以通过指定start参数,从上一次找到的索引的下一位开始继续查找,直到遍历完整个字符串。

方法1:循环迭代查找

直接用循环不断更新起始查找位置,收集所有匹配的索引:

import random

country = ['Beekeeper', 'Fly', 'Hornet']
pickedCountry = random.choice(country)
# 假设选中的是'Beekeeper'
target_char = 'e'
indices = []
start_pos = 0

while True:
    try:
        idx = pickedCountry.index(target_char, start_pos)
        indices.append(idx)
        start_pos = idx + 1  # 下一次从当前索引的下一位开始找
    except ValueError:
        # 找不到目标字符时退出循环
        break

print(f"字符'{target_char}'的所有索引:{indices}")
# 输出:字符'e'的所有索引:[1, 3, 4, 7, 8]

方法2:用生成器封装(复用性更强)

如果需要多次查找不同字符,可以把逻辑封装成生成器,更简洁高效:

def find_all_indices(s, char):
    start = 0
    while True:
        start = s.find(char, start)
        if start == -1:
            return
        yield start
        start += 1

# 调用示例
pickedCountry = 'Beekeeper'
all_e_indices = list(find_all_indices(pickedCountry, 'e'))
print(all_e_indices)  # 输出:[1, 3, 4, 7, 8]

补充说明

  • str.index()和str.find()的区别:前者找不到字符会抛出ValueError,后者返回-1,根据场景选择即可。
  • 如果要统计重复次数,直接取结果列表的长度len(indices)就行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 16:50:22