Page 113 -
P. 113

files and exceptions


          Take a closer look at the data


           Look closely at the data. It appears to conform to a specific format:
                               A colon, followed by a     The line spoken by the
             The cast           space character            cast member
             member’s role


                             Man: Is this the right room for an argument?
                             Other Man: I’ve told you once.
                             Man: No you haven’t!

                             Other Man: Yes I have.
                             Man: When?
                             Other Man: Just now.
                             Man: No you didn’t!



           With this format in mind, you can process each line to extract parts of the line
           as required. The split() method can help here:


                                     Man: Is this the right room for an argument?


          Invoke the “split()” method        each_line.split(":")                This tells “split()”
          associated with the “each_line”
          string and break the string
          whenever a “:” is found.                                               what to split on.


                                          Man
                                                          Is this the right room for an argument?

           The split() method returns a list of strings, which are assigned to a list of
           target identifiers. This is known as multiple assignment:

            A list of target identifiers on the left…                   …are assigned the strings returned by “split()”.


                               (role, line_spoken) = each_line.split(":")


              Using the example data from above, “role” is   …“line_spoken”: is assigned the string “Is this
              assigned the string “Man”, whereas…        the right room for an argument?”

                                                                               Well? Is it? §
                                                                                       you are here 4    77
   108   109   110   111   112   113   114   115   116   117   118