Practice mode Python

How does str.find() differ from str.index() when the substring is not present?

Correct answer D. find() returns -1, while index() raises ValueError

Explanation

Both methods return the lowest index where the substring occurs. When it is missing, find() returns -1 and index() raises ValueError. Use find() when absence is expected, but take care that -1 is a valid negative index, so it should not be used directly for slicing.

Report a problem

Answer checked How we write and check questions

Tip: press A, B, C or D to answer, and N for the next question.

Advertisement

Have a question about this answer?

Your email address will not be published. Required fields are marked *

Links and website addresses are not allowed in comments.