Python - Why do the find and index methods work differently?

孤街醉人 提交于 2019-11-29 09:06:35

This has always been annoying ;-) Contrary to one answer, there's nothing special about -1 with respect to strings; e.g.,

>>> "abc"[-1]
'c'
>>> [2, 3, 42][-1]
42

The problem with find() in practice is that -1 is in fact not special as an index. So code using find() is prone to surprises when the thing being searched for is not found - it was noted even before Python 1.0.0 was released that such code often went on to do a wrong thing.

No such surprises occur when index() is used instead - an exception can't be ignored silently. But setting up try/except for such a simple operation is not only annoying, it adds major overhead (extra time) for what "should be" a fast operation. Because of that, string.find() was added in Python 0.9.9 (before then, only string.index() could be used).

So we have both, and that persists even into Python 3. Pick your poison :-)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!