Skip to ContentGo to accessibility page
Introduction to Python Programming

8.3 Searching/testing strings

Introduction to Python Programming8.3 Searching/testing strings

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.

Checkpoint

What is in the phrase?

What is the phrase?; ch 8, video 3

Concepts in Practice

Using in operator to find substrings

1.
What is the output of ("a" in "an umbrella")?
  1. 2
  2. False
  3. True
  4. 1
2.
What is the output of ("ab" in "arbitrary")?
  1. True
  2. False
3.
What is the output of ("" in "string")?
  1. True
  2. False

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.

Checkpoint

for loop using in operator

For loop using in operator; ch 8, video 4

Concepts in Practice

Using in operator within for loop

4.
What is the output of the following code?
for c in "string":
  print(c, end = "")
  1. string
  2. s
    t
    r
    i
    n
    g
  3. s t r i n g
5.
What is the output of the following code?
count = 0
for c in "abca":
  if c == "a":
    count += 1
print(count)
  1. 0
  2. 1
  3. 2
6.
What is the output of the following code?
word = "cab"
for i in word:
  if i == "a":
    print("A", end = "")
  if i == "b":
    print("B", end = "")
  if i == "c":
    print("C", end = "") 
  1. cab
  2. abc
  3. CAB
  4. ABC

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.

Checkpoint

Counting the number of occurrences of a substring

Counting the number of occurrences of a substring; ch 8, video 5

Concepts in Practice

Using count() to count the number of substrings

7.
What is the output of (aaa".count("a"))?
  1. True
  2. 1
  3. 3
8.
What is the output of ("weather".count("b"))?
  1. 0
  2. -1
  3. False
9.
What is the output of ("aaa".count("aa"))?
  1. 1
  2. 2
  3. 3

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.

Checkpoint

Finding the first index of a substring

Finding the first index of a substring; ch 8, video 6

Concepts in Practice

Using find() to locate a substring

10.
What is the output of "banana".find("a")?
  1. 1
  2. 3
  3. 5
11.
What is the output of "banana".find("c")?
  1. 0
  2. -1
  3. ValueError
12.
What is the output of "b".find("banana")?
  1. -1
  2. 0
  3. ValueError

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.

Example 8.4

Getting the time's minute portion

Consider a time value is given as part of a string using the format of "hh:mm" with "hh" representing the hour and "mm" representing the minutes. To retrieve only the string's minute portion, the following code can be used:

    time_string = "The time is 12:50"
    index = time_string.index(":")
    print(time_string[index+1:index+3])

The above code's output is:

    50

Concepts in Practice

Using index() to locate a substring

13.
What is the output of "school".index("o")?
  1. 3
  2. 4
  3. -3
14.
What is the output of "school".index("ooo")?
  1. 3
  2. 4
  3. ValueError
15.
What is the output of the following code?
sentence = "This is a sentence"
index = sentence.index(" ")
print(sentence[:index])
  1. "This"
  2. "This "
  3. "sentence"

Try It

Finding all spaces

Write a program that, given a string, counts the number of space characters in the string. Also, print the given string with all spaces removed.

    Input: "This is great"
    Prints:
    2
    Thisisgreat
Citation/Attribution
Reuse and redistribution of this content in digital or print format:
  • This book may not be used in the training of large language models or otherwise be ingested into large language models or generative AI offerings without OpenStax's prior written permission.
  • This book uses the Creative Commons Attribution-NonCommercial-ShareAlike License, which means that you can reuse and modify the material only for noncommercial purposes, must attribute OpenStax, and must distribute any derivative works under the same license.
  • Any commercial printing of this textbook, including using a local or custom printer, must be approved by OpenStax, and proper citation provided.
  • OpenStax-copyrighted images, activities, assessments, and similar components of this book are subject to the same licensing – CC-BY-NC-SA. They can be used for noncommercial purposes with attribution. Commercial use requires permission.
  • Permission requests: Anyone who intends to incorporate this content (including text, images, and other components) into large language models, use it in AI offerings, use it commercially (including in print), and/or has questions about another use case is welcome to complete our reuse request form.
Attribution information
  • If you are redistributing all or part of this book in a noncommercial print format, then you must include on every physical page the following attribution:

    Access for free at https://openstax.org/books/introduction-python-programming/pages/1-introduction

  • If you are redistributing all or part of this book in a noncommercial digital format, then for every page that includes OpenStax content, you must license the derivative work under the same CC-BY-NC-SA license as the original, and include on every digital page view the following attribution:

    Access for free at https://openstax.org/books/introduction-python-programming/pages/1-introduction

Citation information

The information below includes the information needed to generate citations in most major styles (APA, MLA, etc.); you must reformat and organize the information as needed to fit the requirements of the style. Use the information below to generate a citation. We recommend using a citation tool such as this one.

© Apr 23, 2026 OpenStax. Textbook content produced by OpenStax is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike License. The OpenStax name, OpenStax logo, OpenStax book covers, OpenStax CNX name, and OpenStax CNX logo, and Rice University name, and Rice University logo trademarks, or wordmarks are not subject to the Creative Commons license and may not be reproduced without the prior and express written consent of Rice University.

This book utilizes the OpenStax Python Code Runner. The code runner is developed by Wiley and is All Rights Reserved.