8.7 Searching for Substrings

  • Can search a string for a **substring to
    • count number of occurrences
    • determine whether a string contains a substring
    • determine the index at which a substring resides in a string
  • Each method shown in this section compares characters lexicographically using their underlying numeric values

Counting Occurrences

  • count returns the number of times its argument occurs in a string
In [1]:
sentence = 'to be or not to be that is the question'
In [2]:
sentence.count('to')
Out[2]:
2
  • If you specify as the second argument a start index, count searches only the slice string[start_index:]
In [3]:
sentence.count('to', 12)
Out[3]:
1
  • If you specify as the second and third arguments the start index and end index,count searches only the slice string[start_index:end_index]
In [4]:
sentence.count('that', 12, 25)
Out[4]:
1
  • Like count, the other string methods presented in this section each have start index and end index arguments

Locating a Substring in a String

  • index searches for a substring within a string and returns the first index at which the substring is found; otherwise, a ValueError occurs:
In [5]:
sentence.index('be')
Out[5]:
3
  • rindex performs the same operation as index, but searches from the end of the string
In [6]:
sentence.rindex('be')
Out[6]:
16
  • find and rfind perform the same tasks as index and rindex but return -1 if the substring is not found

Determining Whether a String Contains a Substring

  • To check whether a string contains a substring, use operator in or not in
In [7]:
'that' in sentence
Out[7]:
True
In [8]:
'THAT' in sentence
Out[8]:
False
In [9]:
'THAT' not in sentence
Out[9]:
True

Locating a Substring at the Beginning or End of a String

  • startswith and endswith return True if the string starts with or ends with a specified substring
In [10]:
sentence.startswith('to')
Out[10]:
True
In [11]:
sentence.startswith('be')
Out[11]:
False
In [12]:
sentence.endswith('question')
Out[12]:
True
In [13]:
sentence.endswith('quest')
Out[13]:
False

©1992–2020 by Pearson Education, Inc. All Rights Reserved. This content is based on Chapter 5 of the book Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and the Cloud.

DISCLAIMER: The authors and publisher of this book have used their best efforts in preparing the book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in these books. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.