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

编写find_substr函数实现子串查找并返回起止元组,需用哪些字符串方法?

实现find_substr函数所需的字符串方法

要实现这个子串查找函数,核心用到Python字符串的find()方法,配合内置函数len()即可完成:

  • str.find(substring):该方法会在目标字符串中查找指定子串的首次出现位置,返回子串第一个字符的索引;如果子串不存在则返回-1,这是获取起始位置的关键。
  • len(substring):用来计算子串的长度,起始索引加上这个长度就能得到子串的结束位置(符合示例中左闭右开的区间规则,比如"plan"长度为4,起始索引2,结束就是2+4=6)。

函数实现示例

def find_substr(substring, string):
    start = string.find(substring)
    if start == -1:
        # 子串不存在时可返回None或自定义值,示例未涉及此情况
        return None
    stop = start + len(substring)
    return (start, stop)

# 测试示例
print(find_substr("plan", "I plan to join summer camp"))  # 输出(2, 6)
print(find_substr("su", "summer vacation"))  # 输出(0, 2)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 11:10:33