python为什么两个不同的方法找到并索引

时间:2016-01-02 03:02:23

标签: python python-2.7 python-3.x

我理解find和index方法的工作原理 -

str = "this is bad"
str.find("good")
-1
str.index("good")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found

但是,为同一任务提供两个功能背后的理由是什么?

我发现this是一个很好的答案,并通过

理解

find() - if the string isn't found, -1 that is returned is the same as the index of the last character in the string as so would create confusion

index() - the try-catch that would have to be used would create an overhead for a fast operation

还是我错了?

另外,为什么如果是这种情况,find()方法只能用于字符串? 当然,无论您是在列表还是字符串上使用它,使用index()的开销都是一样的?或者是因为列表的大小通常比字符串大?

0 个答案:

没有答案