15

What's the design thinking behind this?

To me it's easier to do something like

if string.index(substring) > -1:
    # do stuff

than trying to catch an exception. If the substring is not found, at least your program doesn't break.

Someone told me 'returning -1 is a bad pattern'. Why is that?

What is the Pythonic way for checking substring?

4
  • 2
    Don't use str as a variable name. You can't use str type/function if you use str as a variable name. Commented Sep 18, 2014 at 15:35
  • 1
    One can argue that a function should expect reasonable input, and raise an exception when this is violated. Unless you know to check for -1, you could accidentally use the return value incorrectly. Commented Sep 18, 2014 at 15:39
  • Because the documentation says so. Of course, you could use find, if you'd like Commented Sep 18, 2014 at 15:41
  • 1
    Because -1 is a bad sentinel value for "not found"; negative indexing is allowed! (find gets away with it, I guess, because you still have index when you need the "strict" - aka "correct" - behavior) Commented Sep 18, 2014 at 15:44

3 Answers 3

25

str.index() throws an exception; you were perhaps thinking of the str.find() method instead:

if string.find(substring) > -1:

The str.index() documentation explicitly states this:

Like find(), but raise ValueError when the substring is not found.

However, the correct way to test for substring membership is to use in:

if substring in string:
Sign up to request clarification or add additional context in comments.

Comments

3

Because this way at least the return type of the function is fixed. Also your example is not pythonic, it should read:

if str in string:
    # do stuff

Comments

1

Python operates under the principle of "easier to ask for forgiveness than permission" (EAFP), as explained in an answer by Sven Marnach. It allows the code for the common path to be kept together, making the logic easier to understand without inline error handling cluttering the flow. And in a program that uses import threading for non-blocking I/O, reading the variable only once makes time-of-check-to-time-of-use (TOCTTOU) bugs less likely than in look-before-you-leap style that some other languages encourage.

The major drawback of EAFP is that Python's syntax for exception handling doesn't mesh well with functional programming style. You can't catch exceptions for individual elements in the iterable input to a generator expression without defining and naming a function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.