Page 120 -
P. 120

find the substring


           Add extra logic


           Let’s try each approach, then decide which works best here.
           In addition to the split() method, every Python string has the find()
           method, too. You can ask find() to try and locate a substring in another
           string, and if it can’t be found, the find() method returns the value -1. If
           the method locates the substring, find() returns the index position of the
           substring in the string.







              Assign a string to the each_line variable that does not contain a colon, and then use the find() method to
              try and locate a colon:
              >>> each_line = "I tell you, there's no such thing as a flying circus."
              >>> each_line.find(':')
              -1            The string does NOT contain a colon, so “find()” returns -1 for NOT FOUND.
              Press Alt-P twice to recall the line of code that assigns the string to the variable, but this time edit the string to
              include a colon, then use the find() method to try to locate the colon:
              >>> each_line = "I tell you: there's no such thing as a flying circus."
              >>> each_line.find(':')
              10                     The string DOES contain a colon, so “find()” returns a positive index value.







                              And you thought this approach wouldn’t
                              work? Based on this IDLE session, I
                              think this could do the trick.


















           84    Chapter 3
   115   116   117   118   119   120   121   122   123   124   125