liveBook · Manning

Find

As explained in Python How-To

The Python str.find method returns the lowest index at which a specified substring occurs, or -1 if it is absent.

Use str.find when a string search should return the substring’s position without raising an exception when no match exists. It returns the lowest matching index or -1 when the substring is absent. section 4.3.3

Keep these usage rules in mind:

  • Call find on strings only; other sequence types do not provide this method. section 4.3.3
  • Check whether the returned index is greater than or equal to zero before using the match position. section 4.3.3
  • Prefer find or rfind for substring searches when avoiding the ValueError raised by index matters. section 4.3.3

Filtering task content

A task loader can search the title, description, and completion note for requested content. If no field contains a match, it skips the current row with continue; find avoids an exception during that test. section 14.2.3

def find_string(substr):
   str_index = the_str.find(substr)
   if str_index >= 0:
       # do something with the str_index
   else:
       # do something when the substr isn’t present

Use the returned index to separate the match-found path from the substring-absent path. section 4.3.3

How Python How-To covers it

How deep it goes
Defines the return values, string-only scope, and basic conditional pattern, but does not explain implementation internals.
Examples
Demonstrates checking a returned index and filtering task titles, descriptions, and completion notes.
What it assumes
Assumes familiarity with strings, sequence indices, and the index method while distinguishing substring searches from other sequence operations.
What you can do after
Apply it via Python strings to locate substrings and branch safely when no match exists.
How it connects
Connects strings with substring searching, rfind, the index method, ValueError, and conditional filtering.

Also explained in

Compare how 2 books explain find →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.