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

如何利用find()与set()获取字符在字符串中所有出现的索引?

Fixing the Index Collection for All Character Occurrences

Got it, let's get your code working to capture every index where the target character shows up! Your current code only grabs the first match because str.find() stops at the first occurrence by default. We can adjust this with a loop, and also incorporate set() as required to make the existence check more efficient.

Step-by-Step Modified Code

Here's the updated solution that collects all matching indices:

def find_all_indices(input_str, target_char):
    indices = []
    start_pos = 0
    # Use set() to quickly check if the target character exists in the string
    if target_char not in set(input_str):
        return indices
    # Loop until no more matches are found
    while True:
        current_index = input_str.find(target_char, start_pos)
        if current_index == -1:
            break
        indices.append(current_index)
        # Move the starting position past the current match to find the next one
        start_pos = current_index + 1
    return indices

# Example usage matching your test case
x = 'abcabcabc'
y = 'c'
print(find_all_indices(x, y))  # Output: [2, 5, 8]

How It Works

  • set(input_str): Converts the input string into a set of unique characters. Checking if the target exists in a set is faster (O(1) time) than checking directly in a string, which is a nice optimization especially for longer texts.
  • Loop with find(): We start searching from position 0, find the first match, then update the starting position to current_index + 1 so we don't re-find the same character. We repeat this until find() returns -1 (signaling no more matches left).
  • Collect Indices: Every valid index returned by find() gets added to our list, which we return once the loop finishes.

Testing with Your Example

When you run the code with your sample inputs:

  1. First find() locates 'c' at index 2, adds it to the list, then sets the next start position to 3
  2. Next find() locates 'c' at index 5, adds it to the list, sets start position to 6
  3. Third find() locates 'c' at index 8, adds it to the list, sets start position to 9
  4. The next find() returns -1, so the loop breaks and we get the desired output [2,5,8]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 15:04:05