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

Python中str.rfind()是否采用从后向前迭代的实现方式?

str.rfind 是否从字符串末尾向开头迭代?

是的,str.rfind() 底层是从指定范围的末尾向开头迭代查找的,这也是它能返回最高匹配索引的核心原因。

官方文档只明确了它的行为,没有详述实现细节:

Return the highest index in the string where substring sub is found, such that sub is contained within s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure.

你在IDE里看到的只是Python的类型存根,不是实际的底层实现代码:

def rfind(self, sub: str, start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., /) -> int: ...

CPython作为Python的主流实现,str.rfind() 的实际代码在Objects/stringlib/fastsearch.h中,它调用的是反向查找逻辑——从end指定的位置开始往前遍历字符串,一旦匹配到目标子串就返回对应的起始索引,遍历完没找到则返回-1。

作为新手,直接找CPython源码确实有门槛,你也可以通过行为验证:比如在包含重复子串的长字符串中,rfind 总能快速定位到最后一次出现的位置,这和从后往前查找的效率逻辑完全吻合。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 15:02:33