简体   繁体   中英

Why does Python throw an error when a substring is not found?

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?

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:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM