Introduction to Python ProgrammingXYZ Homework Edition

⇩ Download ▾

8.3 Searching/testing strings

Learning objectives

By the end of this section you should be able to

  • Use the in operator to identify whether a given string contains a substring.
  • Call the count method to count the number of substrings in a given string.
  • Search a string to find a substring using the find method.
  • Use the index method to find the index of the first occurrence of a substring in a given string.
  • Write a for loop on strings using in operator.

in operator

The in Boolean operator can be used to check if a string contains another string. in returns True if the first string exists in the second string, False otherwise.

For loop using in operator

The in operator can be used to iterate over characters in a string using a for loop. In each for loop iteration, one character is read and will be the loop variable for that iteration.

count

The count method counts the number of occurrences of a substring in a given string. If the given substring does not exist in the given string, the value 0 is returned.

find

The find method returns the index of the first occurrence of a substring in a given string. If the substring does not exist in the given string, the value of -1 is returned.

index

The index method performs similarly to the find method in which the method returns the index of the first occurrence of a substring in a given string. The index method assumes that the substring exists in the given string; otherwise, throws a ValueError.

Adapted from Introduction to Python Programming by OpenStax (openstax.org), licensed under CC BY-NC-SA 4.0. Changes were made. License: CC-BY-NC-SA-4.0.

These eBooks are a prerelease and are not yet certified conformant with WCAG 2.1 AA or ADA Title II. Every page is built against an automated accessibility gate, and the published editions will meet ADA Title II requirements when they release in late September 2026. If something is unusable, please tell us.