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}\)By the end of this section you should be able to
- Use the
inoperator 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.
What is the output of ("a" in "an umbrella")?
2FalseTrue1
- Answer
-
c. Since
"a"is a substring of"an umbrella", the output of"a"in"an umbrella"isTrue.
What is the output of ("ab" in "arbitrary")?
TrueFalse
- Answer
-
b.
"ab"is not a substring of"arbitrary"; hence, the output isFalse.
What is the output of ("" in "string")?
TrueFalse
- Answer
-
a. Since
""is a substring of length 0 for"string", the output isTrue.
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.
What is the output of the following code?
for c in "string":
print(c, end = "")
-
string
-
s t r i n g
-
s t r i n g
- Answer
-
a. The
forloop iterates through the characters in"string"and prints all character without any separator character.
What is the output of the following code?
count = 0
for c in "abca":
if c == "a":
count += 1
print(count)
012
- 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 be2.
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 = "")
cababcCABABC
- 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.
What is the output of (aaa".count("a"))?
True13
- Answer
-
c.
"aaa".count("a")returns3, which is the number of occurrences of"a"in string"aaa".
What is the output of ("weather".count("b"))?
0-1False
- Answer
-
a. Zero occurrence of
"b"exists in"weather"; hence, the output of"weather".count("b")is0.
What is the output of ("aaa".count("aa"))?
123
- 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.
What is the output of "banana".find("a")?
135
- 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.
What is the output of "banana".find("c")?
0-1ValueError
- Answer
-
b. Since
"c"is not a substring in"banana", thefind()method returns-1.
What is the output of "b".find("banana")?
-10ValueError
- Answer
-
a. Since
"banana"is not a substring of"b",-1is 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.
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
What is the output of "school".index("o")?
34-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.
What is the output of "school".index("ooo")?
34ValueError
- Answer
-
c. Substring
"ooo"does not exist in the string"ooo"and hence theindex()method returns aValueError.
What is the output of the following code?
sentence = "This is a sentence"
index = sentence.index(" ")
print(sentence[:index])
"This""This ""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".
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
- Answer
-
s = "This is great"print(s.count(" "))
output = ""
for c in s:
if c != " ":
output += cprint(output)


