Stephen Hansen <apt.shan...@gmail.com> writes: >>> str.find() returns -1 on failure (i.e. if the substring is not in the >>> given string). >>> -1 is considered boolean true by Python. >> >> That's an odd little quirk... never noticed that before. >> >> I just use regular expressions myself. >> >> Wouldn't this be something worth cleaning up? It's a little confusing >> for failure to evaluate to boolean true even if the relationship isn't >> direct. > > But what would you clean it up to? > > str.find can return 0 ... which is a *true* result as that means it > finds what you're looking for at position 0... but which evaluates to > boolean False. The fact that it can also return -1 which is the > *false* result which evaluates to boolean True is just another side of > that coin. > > What's the options to clean it up? It can return None when it doesn't > match and you can then test str.find("a") is None... but while that > kinda works it also goes a bit against the point of having boolean > truth/falsehood not representing success/failure of the function. 0 > (boolean false) still is a success. > > Raising an exception would be a bad idea in many cases, too. You can > use str.index if that's what you want. > > So there's not really a great solution to "cleaning it up" . I > remember there was some talk in py-dev of removing str.find entirely > because there was no really c, but I have absolutely no idea if they > ended up doing it or not. > > --S
(Sorry all for the multiple post... my gnus fudged a bit there) That's the funny thing about integers having boolean contexts I guess. Here's a case where 0 actually isn't "False." Any returned value should be considered "True" and "None" should evaluate to "False." Then the method can be used in both contexts of logic and procedure. (I guess that's how I'd solve it, but I can see that implementing it is highly improbable) I'm only curious if it's worth cleaning up because the OP's case is one where there is more than one way to do it. However, that's not the way the world is and I suppose smarter people have discussed this before. If there's a link to the discussion, I'd like to read it. It's pedantic but fascinating no less. -- http://mail.python.org/mailman/listinfo/python-list