Finding: find(), rfind(), index(), rindex(), count(), replace()

The finding functions in the string module locate a substring within a string. For example, substrings of “Python is fun” are “Pyt”, “is”, “fun”, “n is f”, and so forth. Using a substring helps in parsing string data.

The find(s, sub, [start],[end]) function finds the first position of a substring in a given string. You can set the start and stop position arguments, which determine where in the string the search will begin and end. Here's an example:

>>> str = "apple peach pear grapes apple lime lemon"
>>> position = find(str, "pear")

Here's a real-world use of find(): extracting text out of a tag when reading in an HTML file from a server.

Create some sample text embedded in HTML ...

Get Python Programming with the Java™ Class Libraries: A Tutorial for Building Web and Enterprise Applications with Jython now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.