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

如何编写Python程序查找指定字符串在目标字符串中的第3次出现位置

查找指定字符串第3次出现位置的Python程序

下面是实现该功能的Python函数,核心思路是通过循环调用str.find()方法,每次找到后更新下一次查找的起始位置,直到定位到第3次出现的位置:

def find_string(main_str, sub_str):
    count = 0
    start_pos = 0
    sub_length = len(sub_str)
    
    # 处理子串为空的特殊情况
    if sub_length == 0:
        return -1
    
    while count < 3:
        current_pos = main_str.find(sub_str, start_pos)
        # 若某次查找失败,说明子串出现次数不足3次
        if current_pos == -1:
            return -1
        count += 1
        # 更新起始位置,避免重复匹配同一子串
        start_pos = current_pos + sub_length
    
    return current_pos

示例调用

result = find_string("I am the the champion of the champions of the champions", "the")
print(result)  # 输出:20

说明

  • 如果子串在主串中出现次数不足3次,函数会返回-1
  • 默认采用非重叠匹配(即找到子串后,下一次从该子串结束的下一个位置开始查找),如果需要支持重叠匹配,只需将start_pos = current_pos + sub_length改为start_pos = current_pos + 1即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 18:55:24