What is the difference between string find and index methods in Python?

Asked

Viewed 157 times

3

I always use the method index to fetch the index of a character in a string in Python. I recently discovered the method find() and I noticed that he does exactly the same thing. Example:

name="Alan Turing"

print(name.index(n))
print(name.find(n))

Both return 3.

Is there any difference in these methods that I’m not seeing?

1 answer

4


They serve the same purpose, the difference is in semantics when an error occurs by not finding what you were looking for.

The find() returns position -1, so after searching you should test if the result was this before doing any operation with it, because if it is not a positive value, it is probably not what you wanted. It is best used when it is expected not to find the target in some situations, that is, the operation is an invalid value, but that there is a chance of it happening, you know this.

The index() makes an exception if you don’t think so, and only won’t break the application if it is treated. Then most people will think, "then just treat". It may be in some cases, but probably in a generic way, because this is a programming error or something very unexpected. This method should only be used when you know that what you are looking for will always be found, so if you do not find it is a serious problem in the application. So use and trust that you thought, if not find, let the application break, or treat instead to be cute, but do not make business rule decisions with this exception.

When I see things like this I realize that at some point Python tried to make the right decision about using exception. Too bad it’s not always like this.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.