Skip to main content
Engineering LibreTexts

8.3: Searching/Testing Strings

  • Page ID
    117573
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

    \( \newcommand{\dsum}{\displaystyle\sum\limits} \)

    \( \newcommand{\dint}{\displaystyle\int\limits} \)

    \( \newcommand{\dlim}{\displaystyle\lim\limits} \)

    \( \newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\)

    ( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\)

    \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

    \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\)

    \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)

    \( \newcommand{\Span}{\mathrm{span}}\)

    \( \newcommand{\id}{\mathrm{id}}\)

    \( \newcommand{\Span}{\mathrm{span}}\)

    \( \newcommand{\kernel}{\mathrm{null}\,}\)

    \( \newcommand{\range}{\mathrm{range}\,}\)

    \( \newcommand{\RealPart}{\mathrm{Re}}\)

    \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

    \( \newcommand{\Argument}{\mathrm{Arg}}\)

    \( \newcommand{\norm}[1]{\| #1 \|}\)

    \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)

    \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    \( \newcommand{\vectorA}[1]{\vec{#1}}      % arrow\)

    \( \newcommand{\vectorAt}[1]{\vec{\text{#1}}}      % arrow\)

    \( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vectorC}[1]{\textbf{#1}} \)

    \( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)

    \( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)

    \( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)

    \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \(\newcommand{\longvect}{\overrightarrow}\)

    \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

    \(\newcommand{\avec}{\mathbf a}\) \(\newcommand{\bvec}{\mathbf b}\) \(\newcommand{\cvec}{\mathbf c}\) \(\newcommand{\dvec}{\mathbf d}\) \(\newcommand{\dtil}{\widetilde{\mathbf d}}\) \(\newcommand{\evec}{\mathbf e}\) \(\newcommand{\fvec}{\mathbf f}\) \(\newcommand{\nvec}{\mathbf n}\) \(\newcommand{\pvec}{\mathbf p}\) \(\newcommand{\qvec}{\mathbf q}\) \(\newcommand{\svec}{\mathbf s}\) \(\newcommand{\tvec}{\mathbf t}\) \(\newcommand{\uvec}{\mathbf u}\) \(\newcommand{\vvec}{\mathbf v}\) \(\newcommand{\wvec}{\mathbf w}\) \(\newcommand{\xvec}{\mathbf x}\) \(\newcommand{\yvec}{\mathbf y}\) \(\newcommand{\zvec}{\mathbf z}\) \(\newcommand{\rvec}{\mathbf r}\) \(\newcommand{\mvec}{\mathbf m}\) \(\newcommand{\zerovec}{\mathbf 0}\) \(\newcommand{\onevec}{\mathbf 1}\) \(\newcommand{\real}{\mathbb R}\) \(\newcommand{\twovec}[2]{\left[\begin{array}{r}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\ctwovec}[2]{\left[\begin{array}{c}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\threevec}[3]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\cthreevec}[3]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\fourvec}[4]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\cfourvec}[4]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\fivevec}[5]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\cfivevec}[5]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\mattwo}[4]{\left[\begin{array}{rr}#1 \amp #2 \\ #3 \amp #4 \\ \end{array}\right]}\) \(\newcommand{\laspan}[1]{\text{Span}\{#1\}}\) \(\newcommand{\bcal}{\cal B}\) \(\newcommand{\ccal}{\cal C}\) \(\newcommand{\scal}{\cal S}\) \(\newcommand{\wcal}{\cal W}\) \(\newcommand{\ecal}{\cal E}\) \(\newcommand{\coords}[2]{\left\{#1\right\}_{#2}}\) \(\newcommand{\gray}[1]{\color{gray}{#1}}\) \(\newcommand{\lgray}[1]{\color{lightgray}{#1}}\) \(\newcommand{\rank}{\operatorname{rank}}\) \(\newcommand{\row}{\text{Row}}\) \(\newcommand{\col}{\text{Col}}\) \(\renewcommand{\row}{\text{Row}}\) \(\newcommand{\nul}{\text{Nul}}\) \(\newcommand{\var}{\text{Var}}\) \(\newcommand{\corr}{\text{corr}}\) \(\newcommand{\len}[1]{\left|#1\right|}\) \(\newcommand{\bbar}{\overline{\bvec}}\) \(\newcommand{\bhat}{\widehat{\bvec}}\) \(\newcommand{\bperp}{\bvec^\perp}\) \(\newcommand{\xhat}{\widehat{\xvec}}\) \(\newcommand{\vhat}{\widehat{\vvec}}\) \(\newcommand{\uhat}{\widehat{\uvec}}\) \(\newcommand{\what}{\widehat{\wvec}}\) \(\newcommand{\Sighat}{\widehat{\Sigma}}\) \(\newcommand{\lt}{<}\) \(\newcommand{\gt}{>}\) \(\newcommand{\amp}{&}\) \(\definecolor{fillinmathshade}{gray}{0.9}\)
    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 \(\PageIndex{1}\)

    What is the output of ("a" in "an umbrella")?

    1. 2
    2. False
    3. True
    4. 1
    Answer

    c. Since "a" is a substring of "an umbrella" , the output of "a" in "an umbrella" is True .

    Concepts in Practice \(\PageIndex{2}\)

    What is the output of ("ab" in "arbitrary")?

    1. True
    2. False
    Answer

    b. "ab" is not a substring of "arbitrary" ; hence, the output is False .

    Concepts in Practice \(\PageIndex{3}\)

    What is the output of ("" in "string")?

    1. True
    2. False
    Answer

    a. Since "" is a substring of length 0 for "string" , the output is True .

    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 \(\PageIndex{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
    Answer

    a. The for loop iterates through the characters in "string" and prints all character without any separator character.

    Concepts in Practice \(\PageIndex{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
    Answer

    c. The given code iterates over characters in string "abca" , and each time character "a" is observed, a counter variable is increased by 1. Since "a" appears twice in "abca" , the output will be 2 .

    Concepts in Practice \(\PageIndex{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
    Answer

    c. The code iterates over the characters in "cab" and prints each character's uppercase equivalent. Therefore, the output is "CAB"

    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 \(\PageIndex{7}\): Using count() to count the number of substrings

    What is the output of (aaa".count("a"))?

    1. True
    2. 1
    3. 3
    Answer

    c. "aaa".count("a") returns 3 , which is the number of occurrences of "a" in string "aaa" .

    Concepts in Practice \(\PageIndex{8}\): Using count() to count the number of substrings

    What is the output of ("weather".count("b"))?

    1. 0
    2. -1
    3. False
    Answer

    a. Zero occurrence of "b" exists in "weather" ; hence, the output of "weather".count("b") is 0 .

    Concepts in Practice \(\PageIndex{9}\): Using count() to count the number of substrings

    What is the output of ("aaa".count("aa"))?

    1. 1
    2. 2
    3. 3
    Answer

    b. Two substrings "aa" exist in "aaa" , one starting from index 0 and one starting from index 1.

    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 \(\PageIndex{10}\)

    What is the output of "banana".find("a")?

    1. 1
    2. 3
    3. 5
    Answer

    a. The find() method returns the index for the first occurrence of the substring in the given string. The index for the first occurrence of "a" is 1.

    Concepts in Practice \(\PageIndex{11}\)

    What is the output of "banana".find("c")?

    1. 0
    2. -1
    3. ValueError
    Answer

    b. Since "c" is not a substring in "banana" , the find() method returns -1.

    Concepts in Practice \(\PageIndex{12}\)

    What is the output of "b".find("banana")?

    1. -1
    2. 0
    3. ValueError
    Answer

    a. Since "banana" is not a substring of "b" , -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.

    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 \(\PageIndex{13}\): Using index() to locate a substring

    What is the output of "school".index("o")?

    1. 3
    2. 4
    3. -3
    Answer

    a. The index() method returns the index of the start of the first occurrence of a substring in the given string. The index of the first occurrence of "o" in "school" is 3.

    Concepts in Practice \(\PageIndex{14}\): Using index() to locate a substring

    What is the output of "school".index("ooo")?

    1. 3
    2. 4
    3. ValueError
    Answer

    c. Substring "ooo" does not exist in the string "ooo" and hence the index() method returns a ValueError.

    Concepts in Practice \(\PageIndex{15}\): Using index() to locate a substring

    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"
    Answer

    a. sentence.index(" ") returns the index of the first space character. The print statement prints the prefix of the sentence ending just before the first space character, so the output is "This" .

    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
    Interactive Code
    s = "This is great"
    
    
     
    Answer

    s = "This is great"

    print(s.count(" "))
    output = ""
    for c in s:
    if c != " ":
    output += c

    print(output)


    This page titled 8.3: Searching/Testing Strings is shared under a CC BY 4.0 license and was authored, remixed, and/or curated by OpenStax via source content that was edited to the style and standards of the LibreTexts platform.