如何编写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
相关产品推荐
相关产品推荐

