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

Python技术问询:不使用起始索引/范围参数,查找单词第2、3次出现的索引

如何在Python中不使用起始索引/范围参数查找单词的第二次出现位置

当然可行!针对你的需求,我整理了两种适合初学者理解的方法,既不用str.find()的起始/范围参数,也避开了复杂的正则表达式:

方法一:通过分割单词列表计算位置

这种思路是先把句子拆成单词列表,找到目标单词的所有出现位置,再通过计算前面内容的总长度来得到起始索引:

sentence = "Sammy likes to swim in the ocean, likes to spin servers, and likes to smile."
target_word = "likes"

# 把句子按空格分割成单词列表
word_list = sentence.split()
# 收集所有目标单词在列表中的索引
target_indices = [idx for idx, word in enumerate(word_list) if word == target_word]

# 检查是否至少出现两次
if len(target_indices) >= 2:
    # 计算第二个出现的起始索引:前面所有单词的长度总和 + 空格数(等于前面的单词数量)
    second_start_idx = sum(len(word) for word in word_list[:target_indices[1]]) + target_indices[1]
    print(f"第二个'{target_word}'的起始索引是:{second_start_idx}")
else:
    print(f"单词'{target_word}'没有出现第二次")

原理说明:

  • split()会把句子按空格拆成一个个单词,我们先找到所有"likes"在列表里的位置(比如这里是索引1、6、10)
  • 第二个"likes"在列表的第6位,前面有6个单词,所以空格数是6个;再把前面6个单词的长度加起来,总和就是第二个"likes"开始前的所有字符数,也就是它的起始索引。

方法二:多次截取字符串查找

这种方法用str.find()但不使用它的起始参数,而是通过截取第一次出现后的剩余字符串来找到第二次位置:

sentence = "Sammy likes to swim in the ocean, likes to spin servers, and likes to smile."
target_word = "likes"
word_length = len(target_word)

# 第一次查找目标单词的位置
first_occurrence = sentence.find(target_word)
if first_occurrence == -1:
    print(f"单词'{target_word}'未在句子中出现")
else:
    # 截取第一次出现之后的剩余字符串
    remaining_part = sentence[first_occurrence + word_length:]
    # 在剩余字符串中找目标单词的位置
    second_in_remaining = remaining_part.find(target_word)
    if second_in_remaining == -1:
        print(f"单词'{target_word}'没有第二次出现")
    else:
        # 总索引 = 第一次位置 + 单词长度 + 剩余字符串中的位置
        total_second_idx = first_occurrence + word_length + second_in_remaining
        print(f"第二个'{target_word}'的起始索引是:{total_second_idx}")

原理说明:

  • 先找到第一个"likes"的位置,然后把句子从这个位置+单词长度的地方截断,得到剩下的部分
  • 在剩下的部分里再找"likes",找到的位置加上前面截断的长度,就是第二次出现的总起始索引。

两种方法都能满足你的需求,而且逻辑简单,初学者很容易理解~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:01:55