liveBook · Manning

Find

As explained in Get Programming: Learn to code with Python

find is a Python string method that returns the lowest index of a specified substring or -1 when the substring is absent.

find() searches a string for a specified, case-sensitive substring. It returns the substring’s lowest starting index, counting from 0, or -1 when no match exists. The substring must be a string; even the empty string is considered present in every string. section 8.1

Try a few searches

who = "me myself and I" who.find("and") # 10 who.find("you") # -1 who.find("e") # 1 The first result identifies where "and" begins. The second reports that "you" is absent. The third uses the first occurrence of "e". To search from the other direction, use rfind(), which returns the matching substring nearest the end. section 8.1

A useful pattern is to find a separator and then use its index with slicing. For a full name such as "Aqua Man", find(" ") locates the space; the text before it is the first name, and the text after it is the last name. section 12.2

Listing 12.2. Storing the first and last names in variables
space = name1.find(" ")                              #1
name1_first = name1[0:space]                         #2
name1_last = name1[space+1:len(name1)]               #3
space = name2.find(" ")                              #4
name2_first = name2[0:space]                         #4
name2_last = name2[space+1:len(name2)]               #4

Follow the complete name-splitting listing, which saves the space index and slices both names into separate variables. section 12.2

How Get Programming: Learn to code with Python covers it

How deep it goes
Explains case sensitivity, indexing, first matches, missing matches, and a slicing application, but stops short of implementation internals.
Examples
Demonstrates searches in "some_string" and "me myself and I", then splits names such as "Aqua Man" using a space.
What it assumes
Assumes basic strings and indexing, while reinforcing zero-based positions and string slices through a practical name-splitting task.
What you can do after
Apply it to locate substrings or separators, test whether text is present, and guide string slicing.
How it connects
Connects substring search with strings, string indexing, slicing, user input, and the related rfind() operation.

Also explained in

Compare how 2 books explain find →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Get Programming: Learn to code with Python. The section links point to the parts of the book it draws on.