Skip to ContentGo to accessibility pageKeyboard shortcuts menu
OpenStax Logo
Introduction to Python Programming

8.3 Searching/testing strings

Introduction to Python Programming8.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?

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

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

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

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

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 permission.

Want to cite, share, or modify this book? This book uses the Creative Commons Attribution License and you must attribute OpenStax.

Attribution information
  • If you are redistributing all or part of this book in a 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 digital format, then you must 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

© Jul 30, 2024 OpenStax. Textbook content produced by OpenStax is licensed under a Creative Commons Attribution License . The OpenStax name, OpenStax logo, OpenStax book covers, OpenStax CNX name, and OpenStax CNX logo 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.